Java Fundamentals

Graphical User Interfaces in Java

GUI Programming

Building desktop applications with Java Swing and AWT

Introduction to GUI Programming

  • GUI (Graphical User Interface): Visual way for users to interact with programs
  • Console vs GUI:
    • Console: Text-based, sequential input/output
    • GUI: Visual, event-driven, user-friendly
  • Java GUI Frameworks:
    • AWT (Abstract Window Toolkit) - Original, platform-dependent
    • Swing - Modern, lightweight, platform-independent (we'll use this)
    • JavaFX - Newest, rich graphics and media
Swing is the most widely used and well-documented GUI framework for Java

Core Swing Components

Component Purpose
JFrame Main window container
JPanel Container for organizing components
JButton Clickable button
JLabel Display text or images
JTextField Single-line text input
JTextArea Multi-line text input/display
JCheckBox Checkbox for yes/no options
JComboBox Dropdown selection list

Your First JFrame

import javax.swing.*;

public class FirstWindow {
    public static void main(String[] args) {
        // Create the frame
        JFrame frame = new JFrame("My First Window");

        // Set the size (width, height)
        frame.setSize(400, 300);

        // Set close operation
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Center the window on screen
        frame.setLocationRelativeTo(null);

        // Make it visible
        frame.setVisible(true);
    }
}
Important: Always call setVisible(true) last, after all components are added

Adding Components

import javax.swing.*;

public class SimpleApp {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Simple Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 200);

        // Create components
        JLabel label = new JLabel("Enter your name:");
        JTextField textField = new JTextField(20);
        JButton button = new JButton("Click Me!");

        // Create a panel to hold components
        JPanel panel = new JPanel();
        panel.add(label);
        panel.add(textField);
        panel.add(button);

        // Add panel to frame
        frame.add(panel);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

Layout Managers

Layout managers control how components are arranged in containers:

  • FlowLayout: Components flow left-to-right, top-to-bottom (default for JPanel)
    panel.setLayout(new FlowLayout());
  • BorderLayout: Five regions: NORTH, SOUTH, EAST, WEST, CENTER (default for JFrame)
    frame.setLayout(new BorderLayout());
    frame.add(button, BorderLayout.NORTH);
    frame.add(textArea, BorderLayout.CENTER);
  • GridLayout: Grid of equal-sized cells
    panel.setLayout(new GridLayout(3, 2)); // 3 rows, 2 columns

BorderLayout Example

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

public class BorderLayoutDemo {
    public static void main(String[] args) {
        JFrame frame = new JFrame("BorderLayout Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 400);

        // BorderLayout is default for JFrame
        frame.add(new JButton("North"), BorderLayout.NORTH);
        frame.add(new JButton("South"), BorderLayout.SOUTH);
        frame.add(new JButton("East"), BorderLayout.EAST);
        frame.add(new JButton("West"), BorderLayout.WEST);
        frame.add(new JTextArea("Center"), BorderLayout.CENTER);

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

Event Handling: Introduction

  • Event-Driven Programming: Program responds to user actions (clicks, key presses, etc.)
  • Event: Something that happens (button click, mouse move, key press)
  • Listener: Object that waits for and handles events
  • Common Listeners:
    • ActionListener - Button clicks, menu selections
    • MouseListener - Mouse clicks, enter, exit
    • KeyListener - Keyboard input
Event listeners are interfaces that you implement to handle events

ActionListener with Lambda

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

public class ButtonClickApp {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Button Click Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 150);

        JButton button = new JButton("Click Me!");
        JLabel label = new JLabel("Not clicked yet");

        // Add action listener using lambda (modern Java)
        button.addActionListener(e -> {
            label.setText("Button was clicked!");
        });

        JPanel panel = new JPanel();
        panel.add(button);
        panel.add(label);

        frame.add(panel);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

ActionListener with Anonymous Class

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

public class CounterApp {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Counter");
        JButton button = new JButton("Increment");
        JLabel label = new JLabel("Count: 0");

        // Anonymous class implementation
        button.addActionListener(new ActionListener() {
            private int count = 0;

            @Override
            public void actionPerformed(ActionEvent e) {
                count++;
                label.setText("Count: " + count);
            }
        });

        JPanel panel = new JPanel();
        panel.add(button);
        panel.add(label);
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 100);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

Using Text Fields

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

public class GreetingApp {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Greeting App");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 150);

        JLabel nameLabel = new JLabel("Your name:");
        JTextField nameField = new JTextField(15);
        JButton greetButton = new JButton("Greet");
        JLabel outputLabel = new JLabel("");

        greetButton.addActionListener(e -> {
            String name = nameField.getText();
            outputLabel.setText("Hello, " + name + "!");
        });

        JPanel panel = new JPanel(new FlowLayout());
        panel.add(nameLabel);
        panel.add(nameField);
        panel.add(greetButton);
        panel.add(outputLabel);

        frame.add(panel);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

Complete Example: Simple Calculator

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

public class SimpleCalculator {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Simple Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(350, 200);

        // Create components
        JTextField num1Field = new JTextField(10);
        JTextField num2Field = new JTextField(10);
        JLabel resultLabel = new JLabel("Result: ");

        JButton addButton = new JButton("+");
        JButton subButton = new JButton("-");
        JButton mulButton = new JButton("×");
        JButton divButton = new JButton("÷");

        // Add event listeners
        addButton.addActionListener(e -> calculate(num1Field, num2Field, resultLabel, "+"));
        subButton.addActionListener(e -> calculate(num1Field, num2Field, resultLabel, "-"));
        mulButton.addActionListener(e -> calculate(num1Field, num2Field, resultLabel, "*"));
        divButton.addActionListener(e -> calculate(num1Field, num2Field, resultLabel, "/"));

        // Layout
        JPanel inputPanel = new JPanel();
        inputPanel.add(new JLabel("Number 1:"));
        inputPanel.add(num1Field);
        inputPanel.add(new JLabel("Number 2:"));
        inputPanel.add(num2Field);

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(addButton);
        buttonPanel.add(subButton);
        buttonPanel.add(mulButton);
        buttonPanel.add(divButton);

        frame.setLayout(new BorderLayout());
        frame.add(inputPanel, BorderLayout.NORTH);
        frame.add(buttonPanel, BorderLayout.CENTER);
        frame.add(resultLabel, BorderLayout.SOUTH);

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

    private static void calculate(JTextField num1, JTextField num2,
                                   JLabel result, String operation) {
        try {
            double n1 = Double.parseDouble(num1.getText());
            double n2 = Double.parseDouble(num2.getText());
            double res = 0;

            switch (operation) {
                case "+": res = n1 + n2; break;
                case "-": res = n1 - n2; break;
                case "*": res = n1 * n2; break;
                case "/": res = n1 / n2; break;
            }
            result.setText("Result: " + res);
        } catch (NumberFormatException ex) {
            result.setText("Error: Invalid input");
        }
    }
}

Using JTextArea

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

public class TextAreaExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Text Area Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500, 400);

        // Create text area
        JTextArea textArea = new JTextArea(15, 40);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

        // Add scroll pane for large text
        JScrollPane scrollPane = new JScrollPane(textArea);

        JButton clearButton = new JButton("Clear");
        clearButton.addActionListener(e -> textArea.setText(""));

        frame.setLayout(new BorderLayout());
        frame.add(scrollPane, BorderLayout.CENTER);
        frame.add(clearButton, BorderLayout.SOUTH);

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

JCheckBox and JComboBox

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

public class FormExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Registration Form");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 300);

        JPanel panel = new JPanel(new GridLayout(5, 2, 5, 5));

        // Text field
        panel.add(new JLabel("Name:"));
        JTextField nameField = new JTextField();
        panel.add(nameField);

        // Combo box
        panel.add(new JLabel("Country:"));
        String[] countries = {"France", "USA", "UK", "Germany"};
        JComboBox countryBox = new JComboBox<>(countries);
        panel.add(countryBox);

        // Checkbox
        panel.add(new JLabel("Subscribe:"));
        JCheckBox subscribeBox = new JCheckBox("Newsletter");
        panel.add(subscribeBox);

        // Button
        JButton submitButton = new JButton("Submit");
        submitButton.addActionListener(e -> {
            String name = nameField.getText();
            String country = (String) countryBox.getSelectedItem();
            boolean subscribed = subscribeBox.isSelected();
            JOptionPane.showMessageDialog(frame,
                "Name: " + name + "\nCountry: " + country +
                "\nSubscribed: " + subscribed);
        });
        panel.add(submitButton);

        frame.add(panel);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

JOptionPane: Dialog Boxes

import javax.swing.*;

public class DialogExample {
    public static void main(String[] args) {
        // Information message
        JOptionPane.showMessageDialog(null, "Hello, World!");

        // Confirmation dialog
        int choice = JOptionPane.showConfirmDialog(null,
            "Do you want to continue?",
            "Confirm",
            JOptionPane.YES_NO_OPTION);

        if (choice == JOptionPane.YES_OPTION) {
            System.out.println("User clicked Yes");
        }

        // Input dialog
        String name = JOptionPane.showInputDialog(null,
            "Enter your name:");
        System.out.println("Name: " + name);

        // Option dialog
        String[] options = {"Red", "Green", "Blue"};
        int selected = JOptionPane.showOptionDialog(null,
            "Choose a color", "Color Picker",
            JOptionPane.DEFAULT_OPTION,
            JOptionPane.QUESTION_MESSAGE,
            null, options, options[0]);
    }
}

Object-Oriented GUI Design

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

// Better practice: Extend JFrame
public class MyWindow extends JFrame {
    private JTextField nameField;
    private JLabel greetingLabel;

    public MyWindow() {
        // Set up the window
        setTitle("OOP GUI Example");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 150);

        // Initialize components
        initComponents();

        // Set location and make visible
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private void initComponents() {
        nameField = new JTextField(15);
        greetingLabel = new JLabel("");
        JButton greetButton = new JButton("Greet");

        greetButton.addActionListener(e -> handleGreeting());

        JPanel panel = new JPanel();
        panel.add(new JLabel("Name:"));
        panel.add(nameField);
        panel.add(greetButton);
        panel.add(greetingLabel);

        add(panel);
    }

    private void handleGreeting() {
        String name = nameField.getText();
        greetingLabel.setText("Hello, " + name + "!");
    }

    public static void main(String[] args) {
        // Use SwingUtilities to ensure thread safety
        SwingUtilities.invokeLater(() -> new MyWindow());
    }
}

Best Practices

  • Thread Safety: Always create and modify GUI components on the Event Dispatch Thread
    SwingUtilities.invokeLater(() -> new MyWindow());
  • Separation of Concerns: Separate GUI code from business logic
  • Use Layout Managers: Don't use absolute positioning (setBounds)
  • Dispose Resources: Close windows properly with setDefaultCloseOperation
  • Exception Handling: Always handle user input errors gracefully
  • OOP Design: Extend JFrame/JPanel for complex applications

Exercise: Bank Account GUI

Create a GUI application for managing a bank account with the following features:

  1. Display current balance (starts at 0)
  2. Text field to enter amount
  3. Buttons for:
    • Deposit (adds to balance)
    • Withdraw (subtracts from balance)
    • View history (shows all transactions in a JTextArea)
  4. Use proper layout managers (BorderLayout, FlowLayout, or GridLayout)
  5. Validate input (no negative amounts, sufficient balance for withdrawals)
  6. Display success/error messages using JOptionPane
Bonus: Add interest calculation button and display transaction history with timestamps

Key Takeaways

  • Swing Components: JFrame, JPanel, JButton, JLabel, JTextField, JTextArea
  • Layout Managers: FlowLayout, BorderLayout, GridLayout control component positioning
  • Event Handling: ActionListener for button clicks, use lambdas or anonymous classes
  • Best Practice: Use SwingUtilities.invokeLater() for thread safety
  • OOP Design: Extend JFrame for complex applications, separate concerns
Next Steps: Explore JavaFX for modern GUI development, learn about MVC pattern for larger applications

Slide Overview