Hello, aspiring Java GUI developers!
Today, we’ll introduce Java Swing, a part of the Java Foundation Classes (JFC). Swing provides a set of “lightweight” (all-Java language) components that, to the maximum degree possible, work the same on all platforms.The core of Swing is built on a set of components including JFrame (for the window), JPanel (a container for holding components), JButton, JLabel, JTextField, and many more.### 1. Creating a Basic JFrameThe JFrame class creates a window where components like labels, buttons, textfields are added to create a GUI.
Example:
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame(); // Creating a JFrame
frame.setTitle("My First Swing Application");
frame.setSize(300, 200); // Setting size to 300px width and 200px height
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set default close operation
frame.setVisible(true); // Making the frame visible
}
}
2. Adding Components to JFrame
You can add various components to the JFrame. Let’s add a button and a label.Example:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("My First Swing Application");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello, Swing!");
frame.getContentPane().add(label); // Adding label to frame
JButton button = new JButton("Click Me");
frame.getContentPane().add(button); // Adding button to frame
frame.setLayout(new FlowLayout()); // Setting the layout of the frame
frame.setVisible(true);
}
}
In this example, a label and a button are added to the frame. We also set the layout of the frame using FlowLayout, which arranges components in a left-to-right flow, much like lines of text in a paragraph.### Exercise: Create a Simple GUI ApplicationYour task is to create a simple GUI application using Java Swing. Here’s a suggestion:- Create a JFrame with a title.
- Add a JLabel to display a greeting message.
- Add a JTextField to accept user input.
- Add a JButton: When the user clicks the button, update the label to display the text entered in the text field.
Conclusion
Congratulations! You’ve just dipped your toes into the world of Java Swing, a powerful toolkit for building graphical user interfaces.Experiment with different components and layouts to get familiar with Swing. This practical experience will help you understand how to build more complex and interactive GUIs in Java.Happy coding, and enjoy creating your Java GUI applications!