Building a GUI using Swing in Java involves several steps.
Swing is a part of Java's standard library and
provides a rich set of components for creating graphical user interfaces. Here's a basic outline of how you
can create a simple GUI using Swing:
1. Import Swing Components: Start by importing the necessary Swing classes.
2. import javax.swing.*;
3. import java.awt.*;
4. Create the Main Frame: The main window of your application is typically a JFrame.
5. public class MySwingApp {
6. public static void main(String[] args) {
7. JFrame frame = new JFrame("My Swing Application");
8. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
9. frame.setSize(400, 300);
10. frame.setVisible(true);
11. }
12. }
13. Add Components: You can add various components like buttons, labels, text fields, etc.,
to the frame.
14. public class MySwingApp {
15. public static void main(String[] args) {
16. JFrame frame = new JFrame("My Swing Application");
17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18. frame.setSize(400, 300);
19.
20. // Create a panel to hold components
21. JPanel panel = new JPanel();
22. frame.add(panel);
23. placeComponents(panel);
24.
25. frame.setVisible(true);
26. }
27.
28. private static void placeComponents(JPanel panel) {
29. panel.setLayout(null);
30.
31. JLabel userLabel = new JLabel("User");
32. userLabel.setBounds(10, 20, 80, 25);
33. panel.add(userLabel);
34.
35. JTextField userText = new JTextField(20);
36. userText.setBounds(100, 20, 165, 25);
37. panel.add(userText);
38.
39. JButton loginButton = new JButton("Login");
40. loginButton.setBounds(10, 80, 80, 25);
41. panel.add(loginButton);
42. }
43. }
44. Event Handling: Add action listeners to handle user interactions.
.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // Handle button
click event System.out.println("Login button clicked"); } }); ```
1. Run the Application: Compile and run your application to see the GUI in action.
This is a very basic example, but Swing provides many more components and layout managers to create
complex and responsive GUIs. You can explore classes like JButton, JLabel, JTextField, JPanel, and layout
managers like BorderLayout, FlowLayout, and GridLayout for more advanced designs.