Overviewof Swing
๐จ Swing in Java
Swing is a GUI toolkit in Java used to create rich desktop applications. It is part of the Java Foundation Classes (JFC) and provides a more powerful and flexible alternative to AWT.
๐งพ What is Swing?
-
Swing is in the
javax.swing
package. -
It builds on top of AWT but does not rely on native GUI components, making it platform-independent in look and behavior.
-
All Swing components are lightweight (they do not depend on OS-specific GUI).
-
Supports pluggable look and feel, MVC architecture, and advanced components like trees, tables, tabbed panes, etc.
๐งฑ Architecture of Swing
Swing follows a Model-View-Controller (MVC) architecture:
-
Model: Holds data
-
View: Renders the component
-
Controller: Handles user interaction
Though this is more simplified in modern Swing development, the separation helps customize behavior and appearance independently.
๐ฏ Features of Swing
Feature | Description |
---|---|
Lightweight | Doesn’t rely on native system components |
Pluggable Look and Feel | Can change appearance dynamically |
Rich Set of Widgets | Includes advanced components (tables, trees, sliders) |
Custom Rendering | Can override painting behavior easily |
Multithreaded | Uses Event Dispatch Thread (EDT) for UI updates |
๐งฐ Commonly Used Swing Components
Component | Description |
---|---|
JFrame | Main window |
JPanel | Generic container |
JButton | Push button |
JLabel | Text label |
JTextField | Single-line input |
JTextArea | Multi-line text input |
JCheckBox | Checkbox |
JRadioButton | Radio button |
JComboBox | Drop-down |
JList | List box |
JTable | Display tabular data |
JTabbedPane | Tabbed panels |
JScrollPane | Scrollbars |
JMenuBar , JMenu , JMenuItem | Menu system |
๐งช Simple Example: Swing Program
๐ Layout Managers in Swing
Swing uses layout managers to organize components:
Layout Manager | Description |
---|---|
FlowLayout | Left to right flow |
BorderLayout | Regions: North, South, East, West, Center |
GridLayout | Table-like layout |
BoxLayout | Components stacked either vertically or horizontally |
GridBagLayout | Advanced grid (most flexible) |
๐ง Event Handling in Swing
Uses the Event Delegation Model like AWT.
Common interfaces:
-
ActionListener
– Button clicks -
ItemListener
– Checkboxes, radio buttons -
KeyListener
– Keyboard input -
MouseListener
– Mouse events
Example:
๐ฆ Important Swing Containers
Container | Description |
---|---|
JFrame | Top-level window |
JDialog | Pop-up dialog |
JPanel | Generic container |
JApplet | Used in applets (older technology) |
๐ Pluggable Look and Feel
Swing supports changing the GUI appearance dynamically:
Other options:
-
Metal (default)
-
Nimbus
-
Motif
-
Windows (on Windows OS)
๐งต Threading in Swing
All GUI code should run on the Event Dispatch Thread (EDT):
Comments
Post a Comment