One name has stood the test of time when considering developing desktop applications with Java: Java Swing. For decades, it’s been the base of Java’s Graphical User Interface, or GUI toolkit, it has been the de facto way to build enterprise applications, developer tools, and even parts of the Android Studio IDE.
But now it is the year 2025, and with the emergence of new frameworks such as JavaFX, one may well ask whether Java Swing is still relevant.
It is an in-depth but easy-to-understand guide into Java Swing. We will take a look into the architecture behind it, make an easy application, and evaluate how Java Swing fits into development today. Whether you are a college student, maintainer of a Legacy System, or just a developer interested in Swing, this blog will give you a practical idea of how Swing works in the real world.
What is Java Swing?
Java Swing is a fully-featured widget toolkit to implement GUIs for windowed desktop applications. The JFC is an extension of the Abstract Window Toolkit (AWT), building on the underlying AWT API. As a second aspect, it has a huge range of rich components (e.g., buttons, text fields, menus, tables, etc.) which are implemented fully in Java, and thus are platform agnostic. Java Swing applications will look and feel the same when run on Windows, macOS, or Linux.
Unlike AWT, its predecessor, which used operating system components, Swing creates its own components based on Java code. That leads to a more consistent look and feel using the “Metal” theme and is more flexible, but the performance of native applications might be degraded when creating complex GUI applications.
Why is Java Swing important?
Java Swing was released in the 1990s and is still important to the Java community for three major reasons:
- Large and maintained legacy codebase: There are a lot of enterprise-level applications written in Swing for banking, finance, and government that would require maintenance and modernization, and such applications will need experts in Swing to do this.
- Maturity and Stability: Java Swing is very stable and reliable for developing complex and mission-critical applications, providing numerous operating system and vendor-agnostic platform compatibility.
- Rapid Prototyping: In Swing, the GUI can be realized very fast for internal tools, admin panels, or even prototypes on the desktop.
A recent JetBrains 2023 Java Developer Survey indicated that, though new frameworks such as JavaFX, Voila, and PyQt continue to gain in popularity, a significant portion of developers are still up to creating desktop applications – many of which have been developed using Swing.
Architecture of Java Swing: Component Hierarchy + MVC Model Explained
The architecture of Java Swing is designed to provide developers with flexibility, modularity, and scalability when developing GUI applications, which is achieved by employing the AWT component hierarchy and implementing the Swing Model-View-Controller (MVC) paradigm. It uses an MVC framework in every UI component.
Let’s break it down step by step.
1. Swing’s Layered Architecture
The Swing architecture is made up of layers, each communicating and interacting in specific ways to build up a GUI application. Each layer has a special function regarding the processing of user input, event dispatching, painting, and data representation. Each layer communicates efficiently and continuously with the others to provide a responsive, consistent, and portable user interface.
Key Hierarchy Levels
- Component (java.awt.Component)
- The root class for all visual objects rendered in the screen.
- Container (java.awt.Container)
- A component that can contain other components.
- Examples: Panel, Frame.
- JComponent (javax.swing.JComponent)
- Extends Container and adds Swing-specific features.
- Examples: JButton, JLabel, JTextField.
- Top-Level Containers
- These form the main window or dialog box in which components are placed.
- Examples:
- JFrame – Main application window
- JDialog – Popup dialog window
- JApplet – For GUI applets in browser (Legacy)
- Intermediate Containers
- These are for laying out a group of controls or to group controls together in a logical manner.
- Examples:
- JPanel – General-purpose container
- JScrollPane – Adds scroll functionality
- JTabbedPane – Organizes multiple tabs
2. Swing and MVC Architecture
Swing employs an MVC architecture to decompose each component into 3 parts: Model (data), View (presentation), and Controller (interactions). This allows you to update data independently from displays, and it allows room for customization.
For example, in a JTable:
- The TableModel is the Model and keeps the data.
- The View will layout and draw the table cells.
- The Controller handles interactions such as selection or editing.
3. Loose Coupling of MVC in Swing
The MVC model of Swing uses the idea of loose coupling, unlike a typical MVC framework, where the View and Controller are sometimes merged. This makes components easier to work with while still permitting a developer to implement a custom model and a custom renderer.
Example: a JList uses a ListModel to store the data, and a developer can provide a custom appearance with a ListCellRenderer without touching any underlying logic.
4. The Event Dispatch Thread (EDT) Role
The Event Dispatch Thread (EDT) plays a crucial role in Swing. The EDT handles three main jobs:
- Rendering – Swing has to render the components to the screen.
- User Interaction – This is where a user event is captured (mouse click, key press, etc.).
- Thread safety – Protecting against thread contention and lock states.
Any UI action should run on the EDT to make the application feel more responsive.
Example:
SwingUtilities.invokeLater(() -> {
new MySwingApp().setVisible(true);
});
This also ensures that the GUI is safely initialized on the EDT.
5. The UI Delegate (Pluggable Look and Feel Layer)
Swing components support the Pluggable Look and Feel (PLAF), which uses a concept called UI Delegate. Each component has its own class that describes what it looks like. Each component also has a dedicated class that describes how it behaves.
For example:
- JButton → ButtonUI
- JTable → TableUI
- JTree → TreeUI
Once the settings change to the UIManager, the UI can be changed globally.
6. Putting It All Together: Swing’s Architectural Flow
Here is how the process occurs step-by-step:
- User Activity: The user either clicks, types, or moves the mouse.
- Event Generation: The component generates or triggers an event (e.g., ActionEvent).
- Event Dispatch: The event is sent to the Event Dispatch Thread (EDT).
- Listener Handling: The registered listener handles the event.
- Model Change: If appropriate, the listener updates the state of the model.
- Repaint: The view is repainted automatically based on the state of the model.
This cycle continues indefinitely, keeping the Swing application responsive and in sync.
Diagram: Simplified Swing Architecture
To get a sense of how Java Swing fits into Java’s GUI toolkit space, we have to measure it against its predecessor, the Abstract Window Toolkit (AWT), and successor, JavaFX. This will help put Swing in perspective, but it will also help you understand why JavaFX is perhaps the de-facto way to create new projects.
Here is a full table that describes the main distinctions:
| Aspect |
AWT |
Swing |
JavaFX |
| Overview |
Original GUI toolkit; platform-dependent and mostly outdated. |
Built on AWT; lightweight, stable, and widely used. |
Modern, hardware-accelerated framework for rich UIs. |
| Architecture |
Heavyweight; uses native OS components. |
Lightweight; renders components in Java. |
Lightweight; uses Prism engine and scene graph. |
| Look & Feel |
Native OS style; varies by platform. |
Pluggable themes like Metal or Nimbus. |
Consistent, CSS-based, modern Modena theme. |
| Components |
Basic (Button, Label, TextField). |
Rich set (JTable, JTree, Tabs, Progress bars). |
Advanced (Charts, WebView, 3D shapes). |
| Performance |
Fast for simple UIs; slows with complex layouts. |
Good for enterprise apps; slower with heavy graphics. |
Excellent; GPU-accelerated for high-performance rendering. |
| Styling |
Minimal customization. |
Customizable via PLAF or painting. |
Fully stylable with CSS and FXML. |
| Multimedia |
None. |
Limited; needs external libraries. |
Built-in audio, video, and web support. |
| 3D Graphics |
Not supported. |
Basic 2D via Graphics2D. |
Native 3D API with camera and lighting. |
| Event Handling |
Uses java.awt.event. |
Same model with extra Swing events. |
Modern, property-based event system. |
| Deployment |
Included in JDK. |
Included in JDK. |
Separate library (post-JDK 11). |
| Learning Curve |
Simple but limited. |
Moderate; requires understanding EDT and layouts. |
Steeper; involves FXML, properties, and bindings. |
| Use Case Today |
Legacy apps only. |
Enterprise and internal tools. |
New, media-rich, cross-platform apps. |
Creating a Basic Java Swing Application
Swing applications follow a clear structure:
- Import Swing classes.
- Create a main container (JFrame).
- Add components (JButton, JLabel, JTextField, etc.).
- Set layout and size.
- Make the frame visible.
Let’s walk through an example.
1. Import Required Packages
All Swing classes belong to the javax.swing package. You also need java.awt for layouts and events.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
2. Create a JFrame (Main Window)
A JFrame is the top-level container that represents your application window.
JFrame frame = new JFrame("My First Swing App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
Explanation:
- setDefaultCloseOperation() ensures the app closes when you click the “X” button.
- setSize() defines the width and height of the window.
3. Add Components
Swing provides a rich set of UI components. Here, we will add a label, a text field, and a button.
JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField(15);
JButton button = new JButton("Greet");
JLabel output = new JLabel("");
4. Handle Events
To make the application interactive, add an ActionListener to the button.
button.addActionListener(e -> {
String name = textField.getText();
output.setText("Hello, " + name + "!");
});
This captures the text entered by the user and displays a greeting message when the button is clicked.
5. Arrange Components with Layouts
Use a layout manager like FlowLayout to control how components are positioned.
frame.setLayout(new FlowLayout());
frame.add(label);
frame.add(textField);
frame.add(button);
frame.add(output);
Other popular layout managers include:
- BorderLayout
- GridLayout
- BoxLayout
- CardLayout
6. Make the Frame Visible
Always run Swing code inside the Event Dispatch Thread (EDT) for thread safety.
SwingUtilities.invokeLater(() -> frame.setVisible(true));
Full Example: A Simple Greeting App
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GreetingApp {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Swing Greeting App");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setLayout(new FlowLayout());
JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField(15);
JButton button = new JButton("Greet");
JLabel output = new JLabel("");
button.addActionListener(e -> {
String name = textField.getText();
output.setText("Hello, " + name + "!");
});
frame.add(label);
frame.add(textField);
frame.add(button);
frame.add(output);
frame.setVisible(true);
});
}
}
Output
When you execute this program, the following will happen:
- A window appears that has the title, “Swing Greeting App.”
- You enter your name and click on “Greet.”
- The application will now output a personalized message, like “Hello, Intellipaat,” just beneath the button you clicked on.
Swing Components and Containers Explained
All Swing applications are designed using components (i.e. the visible parts of the application) and containers (i.e. the holders that arrange those components). Understanding how each works is fundamental to building neat, interactive interfaces.
1. Swing Components
Components are the individual graphical items that allow the user to interact with your program (clicking a button, typing text, selecting an item from a list, etc.).
All Swing components are derived from the javax.swing.JComponent class, which offers additional functionality:
- Double buffering (makes rendering less choppy).
- Tooltips (provide additional information).
- Border support (for the sweet visual touch).
- Keyboard and focus support.
Types of Swing Components
Swing has many components that you can use right off the shelf. This is a list of our most commonly used components grouped by type:
| Category |
Component |
Description |
| Text Components |
JTextField, JTextArea, JPasswordField, JEditorPane |
Used for entering and displaying text. |
| Labels |
JLabel |
Displays static text or images. |
| Buttons |
JButton, JToggleButton, JRadioButton, JCheckBox |
Perform actions or toggle states. |
| Lists and Menus |
JList, JComboBox, JMenu, JMenuItem, JMenuBar |
Provide navigation or selection options. |
| Tables and Trees |
JTable, JTree |
Display structured or tabular data. |
| Progress Indicators |
JProgressBar, JSlider |
Show status or allow range selection. |
| Dialogs |
JOptionPane, JFileChooser, JColorChooser |
Pop-up boxes for messages or input. |
| Others |
JToolTip, JSeparator, JScrollBar |
Utility components for enhanced UX. |
Example: Using Common Components
JLabel label = new JLabel("Name:");
JTextField textField = new JTextField(15);
JButton button = new JButton("Submit");
JCheckBox agree = new JCheckBox("I agree to the terms");
JComboBox<String> countryList = new JComboBox<>(new String[]{"India", "USA", "UK"});
These five lines introduce interactivity, form inputs, and choice options to your GUI, which demonstrates the rapid scaling of Swing for real applications.
2. Swing Containers
Containers are special components that store other components and determine how they are represented on the display, and they are the structural basis of every Swing GUI.
All Swing containers derive from either java.awt.Container or javax.swing.JComponent.
Types of Containers
| Type |
Class |
Purpose |
| Top-Level Containers |
JFrame, JDialog, JApplet, JWindow |
Represent the main window or pop-up dialog. |
| Intermediate Containers |
JPanel, JScrollPane, JTabbedPane, JSplitPane |
Group and organize components logically. |
| Specialized Containers |
JToolBar, JLayeredPane, JRootPane |
Offer advanced grouping or layered UI management. |
Commonly Used Containers Explained
- JFrame – The Main Window
- Acts as the top-level window of most Swing applications,
- acts as a container of other panels or components
- provides title bars, minimize/maximize buttons, and terminating actions.
import javax.swing.*;
public class JFrameExample {
public static void main(String[] args) {
JFrame frame = new JFrame("My Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLocationRelativeTo(null); // Center the window
frame.setVisible(true);
}
}
2. JPanel – General-Purpose Container
- Used for organizing components into logical areas.
-
- Usually set with a layout manager.
import javax.swing.*;
import java.awt.*;
public class JPanelExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JPanel Example");
JPanel panel = new JPanel(); // Uses FlowLayout by default
panel.add(new JLabel("Username:"));
panel.add(new JTextField(10));
panel.add(new JButton("Submit"));
frame.add(panel);
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
3. JDialog – Pop-up Window
- Best for temporary messages, input time or confirmation prompts
- Can be modal (blocks interaction with the main window).
import javax.swing.*;
public class JDialogExample {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Operation Completed Successfully!");
}
}
Or, a custom JDialog example:
import javax.swing.*;
public class CustomDialogExample {
public static void main(String[] args) {
JDialog dialog = new JDialog((JFrame) null, "Custom Dialog", true);
dialog.add(new JLabel("This is a modal dialog.", SwingConstants.CENTER));
dialog.setSize(250, 150);
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
}
4. JScrollPane – Scrollable Area
- Adds scroll bars automatically when content exceeds the displayable area.
import javax.swing.*;
public class JScrollPaneExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JScrollPane Example");
JTextArea textArea = new JTextArea(10, 30);
JScrollPane scrollPane = new JScrollPane(textArea);
frame.add(scrollPane);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
5. JTabbedPane – Tabbed Interface
- Switch back and forth between panels using tabs.
import javax.swing.*;
public class JTabbedPaneExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTabbedPane Example");
JTabbedPane tabs = new JTabbedPane();
tabs.addTab("Home", new JLabel("Welcome to the Home Tab"));
tabs.addTab("Settings", new JLabel("Adjust your preferences here"));
tabs.addTab("About", new JLabel("This is a Java Swing example"));
frame.add(tabs);
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
3. Relationship Between Components and Containers
In Swing, a container contains components, and in some cases a component is designated as a container ( JPanel).
Example:
JFrame frame = new JFrame("Component-Container Example");
JPanel panel = new JPanel();
JButton button = new JButton("Click Me");
panel.add(button);
frame.add(panel);
frame.setSize(300, 200);
frame.setVisible(true);
Here’s what happens:
- The JButton is a component.
- The JPanel is a container holding the button.
- The JFrame is the top-level container showing everything on the screen.
4. Layout Managers in Containers
Each container employs a layout manager that routes the location and size of its components. Common examples include:
- FlowLayout – positions components along a row (the default layout manager for JPanel).
- BorderLayout – divides the container into five separate regions: North, South, East, West, and Center.
- GridLayout – positions components in a matrix.
- BoxLayout – positions components in a single column or a single row.
Example:
frame.setLayout(new BorderLayout());
frame.add(new JButton("Top"), BorderLayout.NORTH);
frame.add(new JButton("Bottom"), BorderLayout.SOUTH);
5. Component Tree Structure
Every Swing user interface could be depicted as a tree of components with the first or top-level container as the tree root, and the other components stemming from it.
JFrame
└── JPanel
├── JLabel
├── JTextField
└── JButton
Java Swing Layout Managers
In Swing, a layout manager is a mechanism that automatically positions and sizes the components inside a container (e.g., JPanel, JFrame). If layout managers did not exist, programmers would need to arrange each component manually using pixel-based coordinates, which is not responsive and will likely break depending on the screen resolution.
Key Benefits:
- Automatically adjusts when the window size is modified.
- It has a similar look on any operating system.
- The code is simplified to arrange the components of a user interface.
Default Layouts:
- JPanel → uses FlowLayout by default.
- JFrame → uses BorderLayout by default.
1. FlowLayout
FlowLayout places components in a row from left to right, wrapping the components to the next row when there is not enough room. FlowLayout is the simplest layout manager in Swing, and is generally used for small panels.
- Components flow horizontally, similar to words in a paragraph.
- Alignment can be LEFT, CENTER (default), or RIGHT.
- When the container is resized, the components are re-positioned.
Syntax:
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
Here, the parameters define:
- Alignment: CENTER
- Horizontal gap: 10 pixels
- Vertical gap: 10 pixels
Example:
import javax.swing.*;
import java.awt.*;
public class FlowLayoutExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("FlowLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// FlowLayout with center alignment, 10px horizontal and vertical gaps
frame.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
// Add buttons
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));
frame.add(new JButton("Button 4"));
frame.setSize(300, 150);
frame.setVisible(true);
});
}
}
Use Case:
Best use case for simple toolbars or dialog boxes where the components are flowing naturally.
2. BorderLayout
BorderLayout allows you to divide the container into five main sections, North, South, East, West, and Center. Each section allows flexibility in placing the components in choose regions (or areas) on the window.
- The only restriction in BorderLayout is that each section can have only one component.
- The Center section will grow automatically when there is free space.
- BorderLayout is excellent for applications with fixed headers, footers, and content area.
Regions:
| Region |
Constant |
Description |
| Top |
BorderLayout.NORTH |
Usually contains menus or titles. |
| Bottom |
BorderLayout.SOUTH |
Often holds buttons or status bars. |
| Left |
BorderLayout.WEST |
Commonly used for navigation. |
| Right |
BorderLayout.EAST |
Used for side panels. |
| Center |
BorderLayout.CENTER |
Main content area. |
Example:
import javax.swing.*;
import java.awt.*;
public class BorderLayoutExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("BorderLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout(10, 10)); // gaps for spacing
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("South"), BorderLayout.SOUTH);
frame.add(new JButton("East"), BorderLayout.EAST);
frame.add(new JButton("West"), BorderLayout.WEST);
frame.add(new JButton("Center"), BorderLayout.CENTER);
frame.setSize(400, 250);
frame.setVisible(true);
});
}
}
Best case are dashboards, main windows, or web like views with multiple sections.
3. GridLayout
GridLayout arranges your components in one grid that is equal in cell size. Each cell can have only one component, and the cells uniformally resize the proportions of their space.
- Components will be add on a row-by-row basis.
- All components are the equal size.
- Ideal for forms, numeric/keypads, and tables.
Syntax:
JPanel panel = new JPanel(new GridLayout(2, 3, 10, 10));
This creates a 2×3 grid with 10-pixel gaps.
Example:
import javax.swing.*;
import java.awt.*;
public class GridLayoutExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("GridLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 2 rows, 3 columns, 10px gaps
frame.setLayout(new GridLayout(2, 3, 10, 10));
// Add six buttons
for (int i = 1; i <= 6; i++) {
frame.add(new JButton("Button " + i));
}
frame.setSize(400, 200);
frame.setVisible(true);
});
}
}
Use Case: Ideal for uniform interfaces like keypads or game boards and data entry forms.
4. BoxLayout
BoxLayout will arrange components either vertically (top to bottom) or horizontally (left to right). BoxLayout will give you more control than FlowLayout with regards to component arrangement, alignment, and spacing.
- When creating a BoxLayout, you will specify the axis to align components in:
- BoxLayout.X_AXIS → horizontal alignment.
- BoxLayout.Y_AXIS → vertical alignment.
- You can use glue and rigid components to control spacing.
Example:
import javax.swing.*;
import java.awt.*;
public class BoxLayoutExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("BoxLayout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); // vertical alignment
panel.add(new JButton("Button 1"));
panel.add(Box.createRigidArea(new Dimension(0, 10))); // fixed space
panel.add(new JButton("Button 2"));
panel.add(Box.createVerticalGlue()); // flexible spacing
panel.add(new JButton("Button 3"));
frame.add(panel);
frame.setSize(200, 200);
frame.setVisible(true);
});
}
}
Use Case: Great for aligning objects such as buttons, fields, or labels either vertically or horizontally with controlled spacing.
Event Handling in Java Swing
As a user interacts with a GUI application, the various components in the application respond to the user’s actions in the form of events. For example, a user might: click a button, type in a text field, or move the mouse over a component. All activities carry the respective meaning as an event. Swing handles events using a listener-based delegation model to separate the generating of events from the handling of events.
Key Elements:
- Event Source: The component that creates the event. Example: JButton.
- Event Object: The object that wraps information about the event that took place. Example: ActionEvent, MouseEvent.
- Event Listener: An interface that has a method that is either called or executed when a user interacts with the event source. Example: ActionListener.
- Event Handler: The code that is executed when the action is taken in the listener method.
Event Delegation Model
The Event Delegation Model in Swing works like this:
- A user interacts with a component.
- The component (event source) generates an event object.
- The event object is then sent to any registered listeners.
- The listener runs the code for handling the event, if such code is present to run.
Advantages:
- Efficient: Only the components being observed will respond to the event.
- Scalable: Multiple listeners can receive events from the same source.
- Organized: Logic for handling events is separate from component logic.
Common Swing Event Listeners
Swing provides many interfaces for listeners. They are organized by the type of event:
| Event Type |
Listener Interface |
Example Use |
| Action Events |
ActionListener |
Button clicks, menu selections |
| Mouse Events |
MouseListener, MouseMotionListener |
Clicking, entering, exiting, dragging |
| Key Events |
KeyListener |
Typing in text fields or components |
| Focus Events |
FocusListener |
When a component gains or loses focus |
| Window Events |
WindowListener |
Window opened, closed, minimized |
| Item Events |
ItemListener |
Checkbox or combobox state changes |
| Change Events |
ChangeListener |
Slider, spinner, or tab changes |
1. Handling Action Events
One of the most common events in Swing is button clicks, and ActionEvents are handled in conjunction with ActionListener.
Example:
import javax.swing.*;
import java.awt.event.*;
public class ActionEventExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Action Event Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click Me");
// Registering ActionListener using lambda expression
button.addActionListener(e -> System.out.println("Button clicked!"));
frame.add(button);
frame.setSize(250, 150);
frame.setVisible(true);
});
}
}
Explanation:
- With addActionListener(), the listener is associated with the button.
- A lambda expression is used to implement actionPerformed which is invoked when the button is clicked.
2. Handling Mouse Events
Mouse events capture clicks, movement, drag events, and its related events. We will choose between implementing MouseListener or MouseAdapter.
Example:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MouseEventExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Mouse Event Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(300, 200));
panel.setBackground(Color.LIGHT_GRAY);
// Registering MouseListener using MouseAdapter
panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at: " + e.getX() + ", " + e.getY());
}
});
frame.add(panel);
frame.pack();
frame.setVisible(true);
});
}
}
Tips:
- MouseAdapter can be used to implement just the methods needed, a benefit over MouseListener, which would require you to implement all five methods.
- Common methods in these listeners are: mousePressed(), mouseReleased(), mouseEntered(), mouseExited(), and mouseClicked().
3. Handling Key Events
Key events can use KeyListener to capture when a key was pressed, released, or typed.
Example:
import javax.swing.*;
import java.awt.event.*;
public class KeyEventExample {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Key Event Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField(15);
// Registering KeyListener using KeyAdapter
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
System.out.println("Key typed: " + e.getKeyChar());
}
});
frame.add(textField);
frame.setSize(300, 100);
frame.setVisible(true);
});
}
}
Tip:
Similarly as MouseAdapter allows you to use just the mouse event methods, KeyAdapter allows you to use the methods you want to use not to implement the methods you are not interested in response to key actions.
Best Practices for Building Swing Applications
- Always use the Event Dispatch Thread (EDT): Update your GUI from the EDT using SwingUtilities.invokeLater(), and move non-graphics-related, CPU-intensive tasks to the background using SwingWorker.
- Decouple your UI from logic: Keep your UI code and your business logic code independent of each other for future maintainability, scalability, and testing.
- Utilize Layout Managers: Avoid absolute positioning and use layout managers like FlowLayout, BorderLayout, GridLayout, or BoxLayout to make UIs more fluid and consistent.
- Use Efficient Event Handling: Use lambda expressions or adapter classes to simplify listeners, and do not perform long operations in event handling methods.
- Usability & Consistent Look and Feel: Ensure a consistent L&F is applied to all components, and emphasize accessibility (tooltips, mnemonics, tab order), and avoid cross-platform L&F differences.
- Resource management: Load images, icons, or fonts properly and dispose of unused frames to prevent memory leaks.
Conclusion
Java Swing is still a rich and versatile framework for building cross-platform desktop applications. Developers can make use of Swing’s rich components, layout managers, and custom graphics features for professional-grade user interfaces, that not only look good but are also interactive and functional.
While developing maintainable and responsive applications, developers should follow best practices such as using the Event Dispatch Thread, separating UI and logic, resource management, and layout managers.
JavaFX does exist but while Swing remains popular in enterprise and legacy applications for its stability, flexibility, and a solid ecosystem that has built up over the years around Java GUI applications.
Java Swing – FAQs
How is Swing different from AWT?
The Swing is a lightweight GUI, entirely written in Java, which is platform-independent, while AWT is heavyweight, relying on the component(s) of the native OS. Swing has more components, a pluggable Look and Feel, and allows custom painting.
What are the main components in Swing?
Swing components include:
- Containers – JFrame, JPanel, JDialog
- Controls – JButton, JLabel, JTextField, JCheckBox
- Advanced Components – JTable, JTree, JTabbedPane, JComboBox
- Layout Manager – BorderLayout, FlowLayout, GridLayout, BoxLayout
What is the Event Dispatch Thread (EDT) in Swing?
The EDT is a special thread in Swing, intended to handle GUI events such as button clicks and repaint requests. All updates to Swing components should be performed on the EDT to make the code thread-safe and avoid UI inconsistencies.
Is it possible to develop modern applications using Java Swing?
Yes, Java Swing is still good to go for desktop applications, primarily in enterprise environments. Though there are newer frameworks like JavaFX, Swing is still reliable because it is mature, stable, and its documentation is extensive.
Can I use Swing and JavaFX together?
Yes, you can integrate Swing and JavaFX with the JFXPanel class. A JFXPanel is a Swing component that can host JavaFX content, enabling you to embed modern JavaFX scenes within a legacy Swing application. This is a common strategy for progressively modernizing a large Swing codebase.