Skip to main content
Java Basics
CHAPTER 27 Beginner

Java GUI Basics with Swing

Updated: May 17, 2026
5 min read

# CHAPTER 27

Java GUI Basics with Swing

1. Introduction

Swing is Java's built-in toolkit for building desktop graphical user interfaces (GUIs). While modern Java apps often use web or JavaFX, understanding Swing teaches fundamental GUI concepts — windows, buttons, layouts, and event-driven programming.

2. JFrame — The Main Window

java
1234567891011
import javax.swing.*;

public class MyWindow {
    public static void main(String[] args) {
        JFrame frame = new JFrame("My First GUI");
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null); // Center on screen
        frame.setVisible(true);
    }
}

3. Common Swing Components

java
1234567
JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField(20);
JButton button = new JButton("Submit");
JTextArea textArea = new JTextArea(5, 20);
JCheckBox checkBox = new JCheckBox("I agree");
JComboBox<String> combo = new JComboBox<>(new String[]{"Java", "Python", "C++"});
JPasswordField password = new JPasswordField(20);

4. Layout Managers

java
12345678910
// FlowLayout — left to right, wrapping
frame.setLayout(new FlowLayout());

// BorderLayout — 5 regions: NORTH, SOUTH, EAST, WEST, CENTER
frame.setLayout(new BorderLayout());
frame.add(new JButton("North"), BorderLayout.NORTH);
frame.add(new JButton("Center"), BorderLayout.CENTER);

// GridLayout — rows × columns grid
frame.setLayout(new GridLayout(3, 2)); // 3 rows, 2 cols

5. Event Handling

java
1234567891011121314
JButton button = new JButton("Click Me!");

// Method 1: ActionListener with lambda
button.addActionListener(e -> {
    JOptionPane.showMessageDialog(null, "Button was clicked!");
});

// Method 2: Implementing ActionListener
button.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Clicked!");
    }
});

6. JOptionPane Dialogs

java
12345678
// Message dialog
JOptionPane.showMessageDialog(null, "Welcome to Java!");

// Input dialog
String name = JOptionPane.showInputDialog("Enter your name:");

// Confirm dialog
int choice = JOptionPane.showConfirmDialog(null, "Are you sure?");

7. Mini Project: Calculator GUI

java
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
import javax.swing.*;
import java.awt.*;

public class CalculatorGUI {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Java Calculator");
        frame.setSize(300, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());

        JTextField display = new JTextField();
        display.setFont(new Font("Arial", Font.BOLD, 24));
        display.setEditable(false);
        frame.add(display, BorderLayout.NORTH);

        JPanel panel = new JPanel(new GridLayout(4, 4, 5, 5));
        String[] buttons = {
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "0", "C", "=", "+"
        };

        StringBuilder input = new StringBuilder();

        for (String text : buttons) {
            JButton btn = new JButton(text);
            btn.setFont(new Font("Arial", Font.BOLD, 18));
            btn.addActionListener(e -> {
                String cmd = e.getActionCommand();
                if (cmd.equals("C")) {
                    input.setLength(0);
                    display.setText("");
                } else if (cmd.equals("=")) {
                    try {
                        // Simple evaluation (production apps use a parser)
                        display.setText("Result");
                    } catch (Exception ex) {
                        display.setText("Error");
                    }
                } else {
                    input.append(cmd);
                    display.setText(input.toString());
                }
            });
            panel.add(btn);
        }

        frame.add(panel, BorderLayout.CENTER);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

8. MCQ Quiz with Answers

Question 1

JFrame is:

Question 2

Which layout arranges in a grid?

Question 3

ActionListener handles:

Question 4

JTextField is for:

Question 5

JOptionPane shows:

Question 6

setVisible(true) does what?

Question 7

BorderLayout has how many regions?

Question 8

EXITONCLOSE does what?

Question 9

JPanel is a:

Question 10

Swing is part of:

9. Summary

Swing provides Java desktop GUI components. JFrame is the window, JButton/JTextField/JLabel are widgets, and Layout Managers arrange them. Event handling uses ActionListeners. While modern development favors web UIs, Swing teaches foundational GUI and event-driven programming concepts.

10. Next Chapter Recommendation

In Chapter 28: Java Interview Preparation, we'll compile the most asked Java interview questions with detailed answers and coding challenges.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·