Java Swing is a lightweight GUI toolkit that allows developers to create graphical user interfaces in Java. It is part of the javax.swing package and provides rich, platform-independent GUI components.
Lightweight components → Written entirely in Java, independent of OS
Rich set of components → Buttons, text fields, labels, tables, trees, etc.
Pluggable Look and Feel (L&F) → Can mimic native OS or custom themes
Event-driven programming → Responds to user actions like clicks, typing, etc.
Supports MVC architecture → Separates data (model) from UI (view)
| Component | Description |
|---|---|
JFrame | Main window/container |
JPanel | Panel to hold other components |
JButton | Clickable button |
JLabel | Display text or images |
JTextField | Single-line text input |
JTextArea | Multi-line text input |
JCheckBox | Selectable box |
JRadioButton | Select one option from a group |
JComboBox | Drop-down selection |
JTable | Display tabular data |
Create a JFrame – main window
Add Components – buttons, labels, text fields, etc.
Set Layout Manager – control component arrangement (FlowLayout, BorderLayout, GridLayout)
Add Event Listeners – handle user actions
Make JFrame visible
Output:
Window with a label, text field, and button
On clicking the button, a greeting message pops up
FlowLayout → Components arranged left to right
BorderLayout → Divides container into North, South, East, West, Center
GridLayout → Components arranged in a grid of rows and columns
BoxLayout → Components arranged vertically or horizontally
Swing uses event-driven programming
Events are captured using listeners, e.g., ActionListener, MouseListener, KeyListener
Methods like addActionListener() attach event handlers to components
Platform-independent GUI
Rich and flexible components
Supports MVC architecture
Easy integration with Java 2D API for graphics
Pluggable look and feel
Swing is lightweight and pure Java
All components inherit from JComponent
Use event listeners to handle user actions
Combine layout managers for flexible UI design
Use JOptionPane for dialogs and messages
Java Swing provides a robust, flexible, and platform-independent GUI toolkit. Mastery of Swing enables building interactive desktop applications with buttons, forms, tables, and custom graphics, making Java applications user-friendly and professional.
Take quizzes related to this topic and see where you stand!
Start Quiz Now