Java Swing: Building Graphical User Interfaces


Introduction to Java Swing

Java Swing is a set of graphical user interface (GUI) components that provide a rich and flexible framework for building desktop applications. Swing offers a wide range of components such as buttons, labels, text fields, and more, allowing you to create interactive and visually appealing applications.


Getting Started with Swing

To use Swing, you typically create a JFrame (the main window) and add various Swing components to it. Here's a simple "Hello, Swing!" example:


import javax.swing.*;
public class HelloWorldSwing {
public static void main(String[] args) {
// Create a JFrame (window)
JFrame frame = new JFrame("Hello, Swing!");
// Create a JLabel (text label)
JLabel label = new JLabel("Hello, Swing!");
// Add the label to the frame
frame.add(label);
// Set the frame size and close operation
frame.setSize(300, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make the frame visible
frame.setVisible(true);
}
}

Swing Components

Swing provides a wide range of components, including:

  • JFrame: The main application window.
  • JButton: A clickable button.
  • JLabel: A non-editable text display.
  • JTextField: A single-line text input field.
  • JTextArea: A multi-line text input field.
  • JCheckBox: A checkbox for selecting options.
  • JRadioButton: Radio buttons for exclusive selections.
  • JComboBox: A dropdown list of options.
  • JList: A scrollable list of items.
  • JTable: A table for displaying data.
  • And many more...

Event Handling in Swing

To make Swing components interactive, you can handle events. For example, you can respond to button clicks by adding an action listener to a button component.


import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonClickExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Button Click Example");
JButton button = new JButton("Click Me");
// Add an ActionListener to handle button clicks
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Button Clicked!");
}
});
frame.add(button);
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new java.awt.FlowLayout());
frame.setVisible(true);
}
}

Conclusion

Java Swing is a powerful framework for creating graphical user interfaces in Java. You've learned how to get started with Swing, create Swing components, and handle events in this guide. As you continue to explore Java Swing, you'll discover the versatility and capabilities it offers for building desktop applications.