Build a Java Desktop App with Swing ☕

A Beginner's Guide to Creating a Simple GUI Application.

Step 0: Prerequisites & Goal 🎯
Project Goal

To create a simple desktop window with three components:

  • A text field to enter a name.
  • A button to submit the name.
  • A label to display the greeting.
What You'll Need
  • Java Development Kit (JDK) installed on your system.
  • A simple text editor or a Java IDE like IntelliJ IDEA, Eclipse, or VS Code.
No External Libraries Needed! Java Swing is included with the standard JDK, so you don't need to download or install anything extra.
Step 1: The Basic Window (The `JFrame`) 🖼️

The main window of any Swing application is called a `JFrame`. Let's create a class for our application that extends `JFrame` to inherit all the properties of a window.

Create a new file named `GreeterApp.java` and add the following basic structure:

import javax.swing.*;

public class GreeterApp extends JFrame {

    // The constructor is where we'll set up our window
    public GreeterApp() {
        // 1. Set the title of the window
        setTitle("Greeter App");

        // 2. Set the size of the window (width, height)
        setSize(400, 150);

        // 3. Tell the program to exit when the window is closed
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        // Create and show the GUI on the Event Dispatch Thread
        SwingUtilities.invokeLater(() -> {
            GreeterApp app = new GreeterApp();
            app.setVisible(true); // 4. Make the window visible
        });
    }
}
Key Concept: The Event Dispatch Thread (EDT). The `SwingUtilities.invokeLater()` is a rule in Swing that ensures all GUI-related code runs on a special, dedicated thread. This keeps the user interface responsive and prevents freezing. For now, just remember to always create and show your `JFrame` inside it.
Step 2 & 3: Adding Components & Managing Layout 🧩

An empty window isn't very useful. We need to add our components (also called widgets). We also need a **Layout Manager** to tell Swing how to arrange them.

We will use `FlowLayout`, the simplest layout manager, which places components one after another in a row.

Let's modify our `GreeterApp.java` file.

import javax.swing.*;
import java.awt.*; // Import for FlowLayout
import java.awt.event.*; // Import for event handling (we'll use this in the next step)

public class GreeterApp extends JFrame {

    // Declare our components as instance variables
    private JLabel instructionLabel;
    private JTextField nameField;
    private JButton greetButton;
    private JLabel greetingLabel;

    public GreeterApp() {
        setTitle("Greeter App");
        setSize(400, 150);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // --- LAYOUT ---
        // Set the layout manager for the window
        setLayout(new FlowLayout());

        // --- COMPONENTS ---
        // 1. Create the components
        instructionLabel = new JLabel("Enter your name:");
        nameField = new JTextField(15); // 15 is the approximate width
        greetButton = new JButton("Greet!");
        greetingLabel = new JLabel(""); // Initially empty

        // 2. Add the components to the window's content pane
        add(instructionLabel);
        add(nameField);
        add(greetButton);
        add(greetingLabel);
    }
    
    // main method remains the same
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            GreeterApp app = new GreeterApp();
            app.setVisible(true);
        });
    }
}

If you compile and run the code now, you'll see a window with all the components arranged in a line. However, clicking the button does nothing yet.

Step 4: Event Handling (Making it Interactive) ✨

GUI applications are **event-driven**. They wait for the user to do something (like click a button) and then react to that event. We need to attach an **`ActionListener`** to our button to define what happens when it's clicked.

We will add this logic inside the `GreeterApp` constructor, right after we create the components.

// ... inside the GreeterApp constructor, after adding components ...

// --- EVENT HANDLING ---
// Add an ActionListener to the button.
// We'll use a lambda expression for concise code.
greetButton.addActionListener(e -> {
    // This is the code that runs when the button is clicked
    String name = nameField.getText(); // Get text from the text field
    
    // Check if the name is not empty
    if (!name.trim().isEmpty()) {
        greetingLabel.setText("Hello, " + name + "!"); // Set the label's text
    } else {
        greetingLabel.setText("Please enter a name.");
    }
});
Key Concept: Lambda Expressions. The `e -> { ... }` syntax is a modern Java feature (Java 8+) called a lambda expression. It's a clean and simple way to provide a block of code to be executed later, which is perfect for event listeners.
Step 5: The Complete Program & How to Run It 🏁

Here is the final, complete code for `GreeterApp.java`. You can copy this into a file and run it.

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

public class GreeterApp extends JFrame {

    private JLabel instructionLabel;
    private JTextField nameField;
    private JButton greetButton;
    private JLabel greetingLabel;

    public GreeterApp() {
        setTitle("Greeter App");
        setSize(400, 150);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        instructionLabel = new JLabel("Enter your name:");
        nameField = new JTextField(15);
        greetButton = new JButton("Greet!");
        greetingLabel = new JLabel("");

        add(instructionLabel);
        add(nameField);
        add(greetButton);
        add(greetingLabel);

        greetButton.addActionListener(e -> {
            String name = nameField.getText();
            if (!name.trim().isEmpty()) {
                greetingLabel.setText("Hello, " + name + "!");
            } else {
                greetingLabel.setText("Please enter a name.");
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            GreeterApp app = new GreeterApp();
            app.setVisible(true);
        });
    }
}
How to Run the Application

1. Using an IDE (Recommended):

Simply open the `GreeterApp.java` file in IntelliJ, Eclipse, or another Java IDE and click the "Run" button next to the `main` method.

2. Using the Command Line:

Open a terminal, navigate to the folder where you saved `GreeterApp.java`, and run these two commands:

# Compile the Java code into bytecode
javac GreeterApp.java

# Run the compiled program
java GreeterApp

A window should appear on your screen. Type your name and click the button!

Congratulations! You've Built a Java GUI Application! 🎉

You have successfully created a working desktop application with an interactive graphical interface. This is a huge step beyond console programs!

You learned the three core concepts of Swing GUI development:


This is the foundation for building much more complex and powerful desktop applications. You can now explore different layout managers (like `BorderLayout` or `GridLayout`), more components, and more complex event handling.