Java Swing is a part of Java Foundation Classes (JFC) that provides a rich set of GUI components for Java applications. It is built on top of AWT (Abstract Window Toolkit) but is lightweight, meaning it doesn’t depend on the native system. Instead, Swing components are rendered entirely in Java.
Swing is based on the Model-View-Controller (MVC) architecture. Each component in Swing separates the data (Model), presentation (View), and control logic (Controller). This separation allows for more modular and maintainable code.
Here are some of the most commonly used Swing components:
To create a simple Swing application, you can follow these steps:
Let’s build a simple Swing application that calculates the sum of two numbers. This application will demonstrate how to create a JFrame, add components, and handle events.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleCalculator extends JFrame {
private JTextField num1Field;
private JTextField num2Field;
private JButton addButton;
private JLabel resultLabel;
public SimpleCalculator() {
setTitle("Simple Calculator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
num1Field = new JTextField(10);
num2Field = new JTextField(10);
addButton = new JButton("Add");
resultLabel = new JLabel("Result: ");
add(num1Field);
add(num2Field);
add(addButton);
add(resultLabel);
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addNumbers();
}
});
}
private void addNumbers() {
try {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
double sum = num1 + num2;
resultLabel.setText("Result: " + sum);
} catch (NumberFormatException e) {
resultLabel.setText("Please enter valid numbers.");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SimpleCalculator calculator = new SimpleCalculator();
calculator.setVisible(true);
});
}
}
SimpleCalculator
that extends JFrame
.FlowLayout
.main
method creates an instance of the SimpleCalculator
and sets it visible on the Event Dispatch Thread (EDT).Swing provides several layout managers to control the positioning and sizing of components. Here are some common layout managers:
Let’s modify our previous example to use a GridLayout
for better organization.
public class GridCalculator extends JFrame {
public GridCalculator() {
setTitle("Grid Calculator");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 2));
JTextField num1Field = new JTextField(10);
JTextField num2Field = new JTextField(10);
JButton addButton = new JButton("Add");
JLabel resultLabel = new JLabel("Result: ");
add(num1Field);
add(num2Field);
add(addButton);
add(resultLabel);
addButton.addActionListener(e -> {
double num1 = Double.parseDouble(num1Field.getText());
double num2 = Double.parseDouble(num2Field.getText());
double sum = num1 + num2;
resultLabel.setText("Result: " + sum);
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
GridCalculator calculator = new GridCalculator();
calculator.setVisible(true);
});
}
}
Custom Look-and-Feel: You can change the appearance of your Swing application by using different look-and-feel options provided by the UIManager
class.
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
2.Menus and Toolbars: You can create menus and toolbars using JMenuBar
, JMenu
, and JToolBar
components
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.addActionListener(e -> System.exit(0));
fileMenu.add(exitItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
3.Dialogs: Swing provides pre-built dialog boxes for various tasks, such as showing messages, asking for confirmation, or getting user input.
JOptionPane.showMessageDialog(this, "Hello, World!");
Swing uses the delegation event model, which means that components (the source) notify listeners (the handlers) about events. You can implement event listeners by defining classes that implement the required interfaces or using lambda expressions (as seen in our examples).
Common event interfaces include: