Getting Started - potatoscript/JavaSwing GitHub Wiki

Getting Started with Java Swing

Introduction

Java Swing is a GUI (Graphical User Interface) toolkit that allows developers to create cross-platform desktop applications in Java. It is part of Java Foundation Classes (JFC) and provides a rich set of components for building modern UIs.

Why Use Java Swing?

  • Platform Independent – Works on Windows, macOS, and Linux.
  • Lightweight Components – Uses fewer system resources compared to AWT.
  • Customizable UI – Supports Look and Feel customization.
  • Event-Driven Programming – Simplifies handling user interactions.

1️⃣ Setting Up Java Swing

Prerequisites

Ensure you have the following installed:
✔️ Java Development Kit (JDK) 8+
✔️ An IDE (Eclipse, IntelliJ IDEA, or NetBeans)

Verifying Java Installation

Run the following command in your terminal or command prompt:

java -version

Expected Output (Example):

java version "17.0.2" 2022-01-18 LTS

2️⃣ Creating Your First Swing Application

Step 1: Import Required Swing Packages

import javax.swing.*;

Step 2: Create a Basic JFrame Window

import javax.swing.JFrame;

public class MyFirstSwingApp {
    public static void main(String[] args) {
        JFrame frame = new JFrame("My First Swing Application");
        frame.setSize(400, 300); // Width x Height
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true); // Display the window
    }
}

Step 3: Explanation

  • JFrame is the main window of a Swing application.
  • setSize(width, height) defines the window dimensions.
  • setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ensures the application closes properly.
  • setVisible(true) makes the window visible.

3️⃣ Adding Components to JFrame

Example: Adding a JButton and an Action Listener

import javax.swing.*;

public class SwingExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Swing Components");
        JButton button = new JButton("Click Me");

        button.addActionListener(e -> JOptionPane.showMessageDialog(frame, "Hello, Swing!"));

        frame.add(button); // Add button to the frame
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(null); // No layout manager
        button.setBounds(150, 100, 100, 50); // Position and size (x, y, width, height)
        frame.setVisible(true);
    }
}

Step 1: Explanation

  • JButton creates a clickable button.
  • JOptionPane.showMessageDialog() displays a pop-up message.
  • setLayout(null) disables layout managers for manual positioning.
  • setBounds(x, y, width, height) positions the button.

4️⃣ Running Your Swing Application

Using Command Line

  1. Save your file as SwingExample.java.
  2. Open a terminal and navigate to the file's directory.
  3. Compile the Java file:
    javac SwingExample.java
    
  4. Run the application:
    java SwingExample
    

Using an IDE

  • Open your project in IntelliJ/Eclipse/NetBeans.
  • Click Run to execute the application.

5️⃣ Understanding Swing’s Event Dispatch Thread (EDT)

Swing is not thread-safe, meaning UI updates should run on the Event Dispatch Thread (EDT).
✅ Best practice: Use SwingUtilities.invokeLater() to ensure safe execution.

Example: Running Swing on EDT

import javax.swing.*;

public class SwingOnEDT {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("Safe Swing Execution");
            frame.setSize(400, 300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        });
    }
}

6️⃣ Summary

🔹 Java Swing is a powerful toolkit for building desktop applications.
🔹 Always use SwingUtilities.invokeLater() for thread safety.
🔹 JFrame, JButton, and JLabel are essential components.