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.
Swing is part of Java's desktop GUI libraries. Most Swing
components are available in the javax.swing package.
Common uses of Swing include:
| 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. |
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);
});
}
}
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.
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.
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.
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:
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.
The getText() method retrieves the text entered
into the text field.
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);
});
}
}
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.
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.
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.
JOptionPane provides ready-made dialog boxes for
displaying messages, receiving input, and asking for confirmation.
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
JOptionPane.showMessageDialog(
null,
"Welcome to Java Swing!"
);
}
}
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.
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. |
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.
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);
});
}
}
Choose the correct answer for each question.