Java Swing GUI Tutorial: Building Desktop Window Applications

import javax.swing.*;

public class SwingQuickStartDemo {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Java Swing Quick Start");
            frame.setSize(380, 220);
            frame.setLayout(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            JLabel label = new JLabel("Enter your name:");
            label.setBounds(30, 20, 140, 25);
            frame.add(label);

            JTextField textField = new JTextField("John");
            textField.setBounds(160, 20, 160, 25);
            frame.add(textField);

            JButton button = new JButton("Submit");
            button.setBounds(120, 70, 120, 30);
            frame.add(button);

            JLabel status = new JLabel("Welcome!");
            status.setBounds(30, 120, 300, 25);
            frame.add(status);

            button.addActionListener(e -> {
                status.setText("Hello, " + textField.getText() + "! Window active.");
                System.out.println("Submitted: " + textField.getText());
            });

            frame.setVisible(true);
        });
    }
}

Terminal & GUI Window Output:

Submitted: John
[GUI Window Rendered: 380x220, Title="Java Swing Quick Start", Status="Hello, John! Window active."]

1. Complete Directory of Java Swing GUI Tutorials 🔝

Java Swing is a platform-independent lightweight GUI toolkit providing rich desktop widgets:

Tutorial Guide Key Class / Method What You Will Build
1. Swing Configuration Eclipse WindowBuilder Configuring Eclipse IDE for visual Swing drag-and-drop design.
2. Component Positioning setBounds(x, y, w, h) Absolute coordinate positioning and layout management.
3. JButton & Clicks JButton, addActionListener Adding clickable buttons to a JFrame window.
4. JTextField to JLabel JTextField.getText() Capturing user text input and displaying it dynamically.
5. JRadioButton Options JRadioButton, ButtonGroup Creating mutually exclusive single-choice option selections.
6. Radio Applications Dynamic UI state Real-world calculator and selection form applications.
7. Multi-Window Transfer Two JFrame dialogs Passing data between parent and child window forms.
8. JTable Tabular Data JTable, JScrollPane Displaying multi-column data grids with headers and scrollbars.
9. JTable with MySQL Data ResultSet → JTable Populating database records dynamically into a desktop table.
10. JFrame Form to MySQL INSERT INTO table Saving user form data from a GUI window into MySQL.
11. Insert & Show Unique ID getGeneratedKeys() Displaying the newly generated auto-increment ID in a GUI label.

« More on Java MySQL Database Exercise Queries

2. Launching Windows Safely on the Event Dispatch Thread (EDT) 🔝

Because Swing components are not thread-safe, all GUI creation and modification should run on the Event Dispatch Thread (EDT) via SwingUtilities.invokeLater():

import javax.swing.*;

public class CreateSimpleFrame {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame("My First Window");
            f.setSize(300, 200);
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            f.setVisible(true);
            System.out.println("Frame created on EDT: " + f.getTitle());
        });
    }
}

Terminal Output:

Frame created on EDT: My First Window

3. Responding to User Clicks with ActionListener & Lambdas 🔝

Java 8+ allows concise lambda expressions for button click handlers (see JButton Tutorial):

import javax.swing.*;

public class ButtonClickLambdaDemo {
    public static void main(String[] args) {
        JButton btn = new JButton("Click Me");
        JLabel lbl = new JLabel("Idle");
        btn.addActionListener(e -> {
            lbl.setText("Button clicked at " + System.currentTimeMillis());
            System.out.println("Action event triggered successfully!");
        });
        btn.doClick();
    }
}

Terminal Output:

Action event triggered successfully!

4. Building Tabular Grids with JTable and DefaultTableModel 🔝

Use DefaultTableModel to add, remove, and update rows dynamically (see JTable Tutorial):

import javax.swing.table.DefaultTableModel;

public class TableModelDemo {
    public static void main(String[] args) {
        String[] cols = {"ID", "Name", "Class", "Mark"};
        DefaultTableModel model = new DefaultTableModel(cols, 0);
        model.addRow(new Object[]{1, "John Deo", "Four", 75});
        model.addRow(new Object[]{2, "Max Ruin", "Three", 85});
        System.out.println("JTable model initialized with " + model.getRowCount() + " rows and " + model.getColumnCount() + " columns.");
    }
}

Terminal Output:

JTable model initialized with 2 rows and 4 columns.

5. Mutually Exclusive Option Choices with JRadioButton & ButtonGroup 🔝

Grouping radio buttons inside a ButtonGroup guarantees that selecting one option automatically unselects all others (see JRadioButton Tutorial):

import javax.swing.*;

public class RadioButtonGroupDemo {
    public static void main(String[] args) {
        JRadioButton r1 = new JRadioButton("Option A", true);
        JRadioButton r2 = new JRadioButton("Option B");
        ButtonGroup group = new ButtonGroup();
        group.add(r1);
        group.add(r2);
        System.out.println("Radio group mutually exclusive: r1=" + r1.isSelected() + ", r2=" + r2.isSelected());
    }
}

Terminal Output:

Radio group mutually exclusive: r1=true, r2=false

6. Bridging Swing GUI Forms with MySQL Database Queries 🔝

Connect your desktop input forms directly to backend databases (see JFrame to MySQL and Unique ID Display):

public class SwingDatabaseBridge {
    public static String buildInsertSql(String name, String cls, int mark) {
        return "INSERT INTO student (name, class, mark) VALUES ('" + name + "', '" + cls + "', " + mark + ")";
    }
    public static void main(String[] args) {
        String sql = buildInsertSql("Arnold", "Four", 90);
        System.out.println("Bridge Query: " + sql);
    }
}

Terminal Output:

Bridge Query: INSERT INTO student (name, class, mark) VALUES ('Arnold', 'Four', 90)

7. Comparison: Java AWT vs Swing vs JavaFX 🔝

Toolkit Architecture Platform Look & Feel Best Use Case
AWT Heavyweight (native OS peers) Tied to native OS appearance Legacy lightweight utility applets.
Swing Lightweight (100% Java) Pluggable Look & Feel (consistent) Standard enterprise desktop GUIs.
JavaFX Modern scene-graph & CSS Hardware-accelerated custom themes Modern multimedia & chart-heavy applications.

8. Common Developer Pitfalls & Traps 🔝

Forgetting frame.setLayout(null) When Using setBounds()

By default, a JFrame uses BorderLayout. If you call component.setBounds(x, y, w, h) without first setting frame.setLayout(null);, the default layout manager ignores your coordinates and stretches the last added component across the entire window!

Forgetting frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

If you omit setDefaultCloseOperation, clicking the window close button (X) merely hides the window (HIDE_ON_CLOSE), leaving the Java background process running in memory indefinitely!

9. Complete Compilable Java Program 🔝

public class SwingHubVerifyDemo {
    public static void main(String[] args) {
        String toolkit = "javax.swing.JFrame";
        if (toolkit.startsWith("javax.swing")) {
            System.out.println("All Java Swing GUI hub verification checks passed!");
        }
    }
}

Terminal Output:

All Java Swing GUI hub verification checks passed!

10. Frequently Asked Questions (FAQ) 🔝

Is Swing included in the standard Java JDK?

Yes! The Swing package (javax.swing.*) and AWT (java.awt.*) are bundled with standard Java SE (JDK 8, 11, 17, 21+), requiring no external JAR installations.

What is the difference between a JFrame and a JPanel?

A JFrame is a top-level OS window with a title bar, minimize, and close buttons; a JPanel is an internal container placed inside a frame to group and organize sub-components.

Why must JTable be added inside a JScrollPane?

Adding a JTable directly to a container causes the column headers to disappear! Wrapping it inside new JScrollPane(table) displays both the column header row and scrollbars.

How do I visually design Swing forms in Eclipse?

Install the Eclipse WindowBuilder plugin, which lets you drag and drop buttons, text fields, and tables directly onto the frame (see Swing Configuration).

How can I connect a Swing submit button to a MySQL database?

See our hands-on tutorials: JFrame to MySQL Table and Displaying Generated ID After Insert.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer