Java Swing Tutorial
100%

Java Swing Tutorial

Java Swing is a GUI (Graphical User Interface) toolkit used to create desktop applications. It provides components such as windows, buttons, labels, text fields, checkboxes, tables, and menus.

1. What Is Java Swing?

Swing is part of Java's desktop GUI libraries. Most Swing components are available in the javax.swing package.

Common uses of Swing include:

  • Student management systems
  • Billing software
  • Login and registration forms
  • Calculator applications
  • Desktop data-entry applications
Remember: Swing is used to build desktop applications, not web pages.

2. Important Swing Components

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

3. Creating Your First JFrame

A JFrame is a top-level window used to display Swing components.

import javax.swing.*;

public class Main {
    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("My First Swing App");

            frame.setSize(400, 300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}
Explanation
  • new JFrame() creates a window.
  • setSize() sets its width and height.
  • setDefaultCloseOperation() specifies the closing behavior.
  • setLocationRelativeTo(null) centers the window.
  • setVisible(true) displays the window.
Output: A window titled "My First Swing App" appears.

4. Using JLabel

The JLabel component displays text or an icon.

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("JLabel Example");

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

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

The label displays the text "Welcome to Java Swing!" inside the window.

5. Using JButton

A JButton creates a button that the user can click.

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            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 creates a window containing a button. To make the button perform an action, we use an event listener.

6. Handling Button Click Events

We can use addActionListener() to perform an action when a button is clicked.

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Button Event");

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

            button.addActionListener(e -> {
                label.setText("Button clicked successfully!");
            });

            JPanel panel = new JPanel();
            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);
        });
    }
}

How it works:

  1. The program creates a button and a label.
  2. The event listener waits for the button to be clicked.
  3. The label's text changes when the event occurs.

7. Using JTextField

A JTextField accepts a single line of text from the user.

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            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().trim();

                if (name.isEmpty()) {
                    label.setText("Please enter your name.");
                } else {
                    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

The getText() method retrieves the text entered into the text field.

8. Using JPasswordField

A JPasswordField is used to accept password input. Its characters are normally displayed as masking symbols.

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Password Example");

            JLabel label = new JLabel("Password:");
            JPasswordField passwordField = new JPasswordField(15);
            JButton button = new JButton("Check");

            button.addActionListener(e -> {
                char[] password = passwordField.getPassword();

                if (password.length == 0) {
                    JOptionPane.showMessageDialog(
                        frame,
                        "Please enter a password."
                    );
                } else {
                    JOptionPane.showMessageDialog(
                        frame,
                        "Password entered."
                    );
                }

                java.util.Arrays.fill(password, '\0');
            });

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

            frame.add(panel);
            frame.setSize(400, 200);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}
Security note: This example only checks whether a password was entered. Real applications must verify passwords securely and should not store them as plain text.

9. Using JCheckBox

A JCheckBox lets users select or deselect an option.

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            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 for agreeing!"
                    );
                } 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 returns whether the checkbox is currently selected.

10. Using JRadioButton

A JRadioButton is useful when the user should choose one option from a group. Use ButtonGroup to make the choices mutually exclusive.

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Radio Button Example");

            JRadioButton male = new JRadioButton("Male");
            JRadioButton female = new JRadioButton("Female");

            ButtonGroup group = new ButtonGroup();
            group.add(male);
            group.add(female);

            JButton button = new JButton("Show Selection");

            button.addActionListener(e -> {
                if (male.isSelected()) {
                    JOptionPane.showMessageDialog(frame, "Male selected");
                } else if (female.isSelected()) {
                    JOptionPane.showMessageDialog(frame, "Female selected");
                } else {
                    JOptionPane.showMessageDialog(
                        frame,
                        "Please select an option."
                    );
                }
            });

            JPanel panel = new JPanel();
            panel.add(male);
            panel.add(female);
            panel.add(button);

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

Without a ButtonGroup, multiple radio buttons can be selected independently.

11. Using JComboBox

A JComboBox displays a drop-down list of choices.

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            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: " + course
                );
            });

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

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

The getSelectedItem() method retrieves the selected item from the drop-down list.

12. Using JOptionPane

JOptionPane provides ready-made dialog boxes for displaying messages, receiving input, and asking for confirmation.

Message Dialog
import javax.swing.JOptionPane;

public class Main {
    public static void main(String[] args) {
        JOptionPane.showMessageDialog(
            null,
            "Welcome to Java Swing!"
        );
    }
}
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. It returns null if the user cancels the dialog.

13. Layout Managers in Swing

Layout managers control how components are arranged inside containers. They help create interfaces that adjust to different window sizes.

Layout Manager Purpose
FlowLayout Places components in a row and wraps them when needed.
BorderLayout Arranges components in five regions.
GridLayout Arranges components in equal-sized rows and columns.
BoxLayout Arranges components vertically or horizontally.
Example: GridLayout
import javax.swing.*;
import java.awt.*;

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Grid Layout");

            frame.setLayout(new GridLayout(2, 2, 10, 10));

            frame.add(new JButton("One"));
            frame.add(new JButton("Two"));
            frame.add(new JButton("Three"));
            frame.add(new JButton("Four"));

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

new GridLayout(2, 2, 10, 10) creates two rows and two columns with horizontal and vertical gaps of 10 pixels.

14. Creating a Simple Login Form

This example combines labels, text fields, a password field, a button, and event handling.

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

public class Main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Login Form");
            frame.setLayout(new GridLayout(3, 2, 10, 10));

            JLabel userLabel = new JLabel("Username:");
            JTextField userField = new JTextField();

            JLabel passLabel = new JLabel("Password:");
            JPasswordField passField = new JPasswordField();

            JButton loginButton = new JButton("Login");

            loginButton.addActionListener(e -> {
                String username = userField.getText().trim();
                char[] password = passField.getPassword();

                if (username.isEmpty() || password.length == 0) {
                    JOptionPane.showMessageDialog(
                        frame,
                        "Please enter username and password."
                    );
                } else {
                    JOptionPane.showMessageDialog(
                        frame,
                        "Form submitted for " + username
                    );
                }

                java.util.Arrays.fill(password, '\0');
            });

            frame.add(userLabel);
            frame.add(userField);
            frame.add(passLabel);
            frame.add(passField);
            frame.add(new JLabel(""));
            frame.add(loginButton);

            frame.setSize(400, 200);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }
}
Important: This is a form demonstration, not a secure authentication system. A real login system must verify credentials against a trusted backend and protect passwords.

15. Practice Assignments

  1. Create a JFrame titled "Student Management System".
  2. Display your name using JLabel.
  3. Create a JButton that changes a label when clicked.
  4. Create a form that accepts a student's name and displays it.
  5. Create a password field and a button to check whether it is empty.
  6. Create a checkbox for accepting terms and conditions.
  7. Create a radio button group for selecting a course type.
  8. Create a combo box containing Java, Python, and PHP.
  9. Display a message using JOptionPane.
  10. Build a simple student registration form using Swing.

Java Swing - Quick Quiz

Choose the correct answer for each question.

1. Which class creates a Swing window?



2. Which method retrieves text from a JTextField?



3. Which component displays a drop-down list?