Java GUI Programming
100%

Java GUI Programming

In this lesson, you will learn how to create graphical user interfaces (GUIs) in Java. A GUI allows users to interact with an application using windows, buttons, labels, text fields, and other visual components.

1. What Is GUI in Java?

GUI stands for Graphical User Interface. It allows users to interact with a program through graphical elements instead of typing every command.

Examples of GUI applications include:

  • Calculator applications
  • Text editors
  • Login forms
  • Student management systems
  • Desktop billing software

Common GUI components include:

  • Window: The main application window.
  • Label: Displays text.
  • Button: Performs an action when clicked.
  • Text field: Accepts a single line of text.
  • Text area: Accepts multiple lines of text.
  • Checkbox: Allows an option to be selected.

2. Java GUI Technologies

Java provides different technologies for building desktop GUIs.

Technology Description
AWT Abstract Window Toolkit; provides basic GUI components.
Swing Provides components such as JFrame, JButton, and JTextField.
JavaFX A separate GUI framework for building modern desktop applications.
Note: In this lesson, we will mainly use Swing because it provides many ready-to-use GUI components.

3. Your First Java GUI Program

The JFrame class is used to create a window in a Swing application.

import javax.swing.JFrame;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("My First GUI");

        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}
Explanation
  • JFrame creates a window.
  • setSize(400, 300) sets the window size.
  • setDefaultCloseOperation() defines what happens when the window closes.
  • setVisible(true) displays the window.
Output: A window titled "My First GUI" opens.

4. Creating a Label

A JLabel displays text or an image in a Swing window.

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Label Example");

        JLabel label = new JLabel("Welcome to Java GUI!");

        frame.add(label);
        frame.setSize(400, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

Output: The window displays the text "Welcome to Java GUI!"

Remember: Use JLabel when you want to display text that the user does not directly edit.

5. Adding a Button

A JButton creates a clickable button.

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Button Example");

        JButton button = new JButton("Click Me");

        frame.add(button);
        frame.setSize(400, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

This program displays a button. To perform an action when the button is clicked, we need event handling.

6. Button Click Event Handling

An event occurs when the user performs an action, such as clicking a button. An ActionListener can respond to a button click.

import javax.swing.*;
import java.awt.event.*;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Event Example");

        JButton button = new JButton("Click Me");
        JLabel label = new JLabel("Click the button");

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                label.setText("Button Clicked!");
            }
        });

        JPanel panel = new JPanel();
        panel.add(button);
        panel.add(label);

        frame.add(panel);
        frame.setSize(400, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
How It Works
  1. A button and label are created.
  2. addActionListener() registers a click listener.
  3. actionPerformed() runs when the button is clicked.
  4. The label text changes to "Button Clicked!".

7. Using a Text Field

A JTextField allows the user to enter a single line of text.

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Text Field Example");

        JTextField textField = new JTextField(15);
        JButton button = new JButton("Show Name");
        JLabel label = new JLabel("Enter your name");

        button.addActionListener(e -> {
            String name = textField.getText();
            label.setText("Hello, " + name);
        });

        JPanel panel = new JPanel();
        panel.add(textField);
        panel.add(button);
        panel.add(label);

        frame.add(panel);
        frame.setSize(450, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

Example: Enter "Rahul" and click Show Name.

Output: Hello, Rahul

8. Using a Text Area

A JTextArea allows the user to enter multiple lines of text.

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Text Area Example");

        JTextArea textArea = new JTextArea(5, 20);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

        JScrollPane scrollPane = new JScrollPane(textArea);

        frame.add(scrollPane);
        frame.setSize(400, 250);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

JScrollPane adds scrolling when the content needs more space. setLineWrap(true) allows long lines to wrap automatically.

9. Using a Checkbox

A JCheckBox allows users to select or clear an option.

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Checkbox Example");

        JCheckBox checkBox = new JCheckBox("I agree to the terms");
        JButton button = new JButton("Submit");

        button.addActionListener(e -> {
            if (checkBox.isSelected()) {
                JOptionPane.showMessageDialog(frame, "Thank you!");
            } else {
                JOptionPane.showMessageDialog(frame, "Please accept the terms.");
            }
        });

        JPanel panel = new JPanel();
        panel.add(checkBox);
        panel.add(button);

        frame.add(panel);
        frame.setSize(400, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

The isSelected() method checks whether the checkbox is selected.

10. Using a Combo Box

A JComboBox displays a drop-down list of choices.

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Combo Box Example");

        String[] courses = {
            "Java", "Python", "Web Development"
        };

        JComboBox<String> comboBox = new JComboBox<>(courses);
        JButton button = new JButton("Show Course");

        button.addActionListener(e -> {
            String course = (String) comboBox.getSelectedItem();
            JOptionPane.showMessageDialog(frame, "Selected: " + course);
        });

        JPanel panel = new JPanel();
        panel.add(comboBox);
        panel.add(button);

        frame.add(panel);
        frame.setSize(400, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

The getSelectedItem() method returns the currently selected item.

11. Using JOptionPane

JOptionPane displays simple message, input, and confirmation dialog boxes.

Message Dialog
import javax.swing.JOptionPane;

public class Main {
    public static void main(String[] args) {
        JOptionPane.showMessageDialog(
            null,
            "Welcome to Java"
        );
    }
}
Input Dialog
import javax.swing.JOptionPane;

public class Main {
    public static void main(String[] args) {
        String name = JOptionPane.showInputDialog(
            "Enter your name:"
        );

        if (name != null) {
            JOptionPane.showMessageDialog(
                null,
                "Hello, " + name
            );
        }
    }
}

The input dialog returns the entered text. If the user cancels, it returns null.

12. Common Java Swing Components

Component Purpose
JFrame Creates a main window.
JPanel Groups components inside a container.
JLabel Displays text or an icon.
JButton Creates a clickable button.
JTextField Accepts single-line text.
JTextArea Accepts multiline text.
JCheckBox Allows independent options to be selected.
JRadioButton Allows one option to be selected from a group.
JComboBox Displays a drop-down list.
JTable Displays data in rows and columns.
JOptionPane Displays dialog boxes.

13. Best Practices for Java GUI Programs

  • Use meaningful labels for buttons and text fields.
  • Validate user input before processing it.
  • Use layout managers instead of relying on fixed component positions.
  • Use event listeners to respond to user actions.
  • Keep GUI code organized and easy to maintain.
  • For Swing applications, create and update GUI components on the Event Dispatch Thread.
Recommended Way to Start a Swing GUI
import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Java GUI");
            frame.setSize(400, 250);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}
Tip: Practice by creating small desktop applications before moving on to larger projects.

14. Practice Assignments

  1. Create a window titled "Student Management System".
  2. Create a window with a label displaying your name.
  3. Create a button that displays a welcome message when clicked.
  4. Create a form with a name text field and a Submit button.
  5. Create a checkbox for accepting terms and conditions.
  6. Create a combo box containing Java, Python, and PHP.
  7. Create a simple login form using username and password fields.
  8. Create a student registration form using Swing components.

Java GUI - Quick Quiz

Choose the correct answer for each question.

1. Which class is used to create a Swing window?



2. Which component is used to create a clickable button?



3. Which method gets text from a JTextField?