Java - Java GUI

Java GUI (Graphical User Interface) refers to the set of tools, libraries, and techniques used to create desktop-based graphical applications in Java. GUI applications allow users to interact visually with the program through windows, buttons, menus, text fields, and other components, rather than typing commands in a console.

Java provides multiple libraries and frameworks for building GUI applications, but the most commonly used are:

  • AWT (Abstract Window Toolkit) – the oldest GUI library.

  • Swing – a more advanced and flexible GUI library built on top of AWT.

  • JavaFX – the modern GUI toolkit, designed to replace Swing.

Let's go step by step.


1. What is a GUI?

A GUI is a user-friendly interface that allows interaction with an application through graphical components instead of command-line text.

Example of GUI elements:

  • Windows

  • Buttons

  • Labels

  • Text fields

  • Checkboxes

  • Menus

  • Tables

In Java, these components are available through libraries like AWT, Swing, and JavaFX.


2. Java GUI Libraries

A. AWT (Abstract Window Toolkit)

  • Introduced in Java 1.0.

  • Provides basic GUI components like buttons, labels, and text fields.

  • Uses native OS components → platform-dependent.

  • Limited customization.

Example:

import java.awt.*;
import java.awt.event.*;

public class AWTExample {
    public static void main(String[] args) {
        Frame frame = new Frame("AWT Example");
        Button button = new Button("Click Me");

        button.setBounds(80, 100, 100, 40);
        frame.add(button);
        frame.setSize(300, 250);
        frame.setLayout(null);
        frame.setVisible(true);

        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                frame.dispose();
            }
        });
    }
}

Limitations of AWT:

  • Heavyweight components.

  • Poor look and feel.

  • Less flexibility compared to Swing and JavaFX.


B. Swing (Part of Java Foundation Classes – JFC)

  • Introduced in Java 1.2.

  • Built on top of AWT but lightweight (doesn’t rely heavily on OS components).

  • Provides rich, customizable components.

  • Platform-independent.

  • Supports MVC (Model-View-Controller) architecture.

  • Still widely used, but JavaFX is preferred for modern apps.

Key Swing Components:

  • JFrame → main window

  • JButton → button

  • JLabel → label for text/images

  • JTextField → single-line text input

  • JTextArea → multi-line text input

  • JTable → tables

  • JMenuBar → menu bar

  • JPanel → container for components

Example:

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

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

        button.setBounds(100, 100, 120, 40);
        frame.add(button);

        frame.setSize(350, 250);
        frame.setLayout(null);
        frame.setVisible(true);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(frame, "Button Clicked!");
            }
        });
    }
}

Advantages of Swing:

  • Cross-platform.

  • Rich set of components.

  • Pluggable look and feel.

  • Easier to customize than AWT.

Disadvantages:

  • Can be slow for complex UIs.

  • Looks outdated compared to modern frameworks.


C. JavaFX (Modern GUI Toolkit)

  • Introduced in Java 8 as a replacement for Swing.

  • Uses Scene Graph API instead of traditional components.

  • Supports CSS styling and FXML (XML-based UI design).

  • Better suited for modern, responsive, multimedia-rich apps.

  • Supports animations, charts, 2D/3D graphics, and audio/video.

Key Components:

  • Stage → main window.

  • Scene → container for UI components.

  • Pane → layout container.

  • Button, Label, TextField, TableView, etc.

Example:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class JavaFXExample extends Application {
    @Override
    public void start(Stage primaryStage) {
        Button button = new Button("Click Me");
        button.setOnAction(e -> System.out.println("Button Clicked!"));

        StackPane root = new StackPane();
        root.getChildren().add(button);

        Scene scene = new Scene(root, 300, 250);
        primaryStage.setTitle("JavaFX Example");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Advantages of JavaFX:

  • Modern and feature-rich.

  • CSS-based styling.

  • Built-in support for charts, 3D, and animations.

  • Better performance than Swing.

Disadvantages:

  • Requires Java 8 or later.

  • Still less popular than Swing in legacy systems.


3. Event Handling in Java GUI

Event handling is the mechanism that controls what happens when a user interacts with GUI components.

  • Uses the Delegation Event Model.

  • Components generate events (e.g., button clicks, key presses).

  • Event Listeners handle those events.

Example (Swing Button Listener):

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        System.out.println("Button clicked!");
    }
});

4. Layout Managers

Layout managers define how components are arranged in a container.

Common layout managers:

  • FlowLayout → arranges components left to right.

  • BorderLayout → divides container into North, South, East, West, Center.

  • GridLayout → organizes components in rows and columns.

  • BoxLayout → arranges components vertically or horizontally.


5. Comparison Table

Feature AWT Swing JavaFX
Introduced In Java 1.0 Java 1.2 Java 8
Lightweight ❌ No ✅ Yes ✅ Yes
Look & Feel OS-dependent Pluggable CSS-based
Performance Low Medium High
Multimedia Limited Limited Advanced
Modern UI ❌ No ⚠️ Outdated ✅ Yes
Recommended For Legacy apps Desktop apps Modern apps

6. When to Use What

  • Use AWT → Only for maintaining very old applications.

  • Use Swing → For desktop apps needing a stable, cross-platform GUI.

  • Use JavaFX → For modern, feature-rich, and interactive applications.


7. Best Practices

  • Always use JavaFX for new projects.

  • Use MVC architecture for maintainable GUI apps.

  • Use layout managers instead of absolute positioning.

  • Use multithreading (e.g., SwingWorker or JavaFX background tasks) for long-running operations.

  • Separate UI and business logic for better scalability.