A Beginner's Guide to Creating a Simple GUI Application.
You've built applications that run in the command line. Now, let's create an application with a visual, interactive interface that users can click and type into. We'll use **Java Swing**, a built-in GUI toolkit that's part of standard Java.
In this tutorial, we will build a simple **"Greeting App"**. A user will be able to enter their name in a text box, click a button, and see a personalized greeting message.
To create a simple desktop window with three components:
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
});
}
}
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.
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.");
}
});
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);
});
}
}
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!
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.