Skip to content
Tutorials Center
My learning

Topics

Lesson 148 of 201 ยท Desktop GUI

Swing Events and a Small App

Handle Swing events with ActionListener lambdas, Actions and document listeners, build a temperature converter app and keep it responsive with SwingWorker.

In Swing Basics you built windows and arranged components. A window that only sits there isn't very useful, though: the interesting part is reacting to the user. In Swing, every click, key press, selection and text change produces an event, and your code runs because you registered a listener for it. Get comfortable with listeners and you can build any Swing application.

This lesson covers the listeners you'll use daily, starting with ActionListener written as a lambda. Then come reusable Action objects, listening to text as the user types, and reading and validating input. All of that is put together in a small temperature converter app. Finally, SwingWorker runs slow tasks in the background without freezing the window. The complete app is read-only (our server has no screen), but the runnable examples use real Swing buttons, labels, models and threads, driven from code exactly as automated GUI tests do.

How Swing events work

Every interactive component is an event source. It keeps a list of listeners and notifies them when something happens:

  1. You register a listener: button.addActionListener(listener).
  2. The user clicks. The operating system tells Java, and Java puts an event in the queue.
  3. The event dispatch thread (EDT) takes the event and calls actionPerformed(ActionEvent e) on every registered listener.
  4. Your code runs, perhaps updating labels or other components, and returns. Then the EDT handles the next event.

Different kinds of events use different listener interfaces:

Listener Method(s) Fired by
ActionListener actionPerformed Button clicks, Enter in a text field, menu items, combo box choice
ItemListener itemStateChanged Check boxes, radio buttons, combo boxes (select/deselect)
ChangeListener stateChanged Sliders, spinners, tabbed panes
DocumentListener insertUpdate, removeUpdate, changedUpdate Text changes in any text component (via its Document)
ListSelectionListener valueChanged Selection in JList and JTable
MouseListener / MouseMotionListener mouseClicked, mousePressed, mouseMoved, ... Mouse activity on any component
KeyListener keyPressed, keyReleased, keyTyped Keys, for the focused component (prefer key bindings)
WindowListener windowClosing, windowOpened, ... Frames and dialogs
FocusListener focusGained, focusLost Any focusable component

ActionListener, ItemListener, ChangeListener and ListSelectionListener have a single method, so they're functional interfaces and you can write them as lambdas. Interfaces with several methods have adapter classes (MouseAdapter, WindowAdapter, KeyAdapter) with empty implementations, so you override only what you need.

ActionListener: lambdas, method references and commands

There are several ways to write the same listener. Lambdas are the modern default; method references keep longer handlers readable; one shared listener can tell buttons apart by their action command. Run this example, which wires up a tiny counter with three buttons:

Java Three ways to write an ActionListener

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The two listeners on Reset both ran for one click. Swing makes no promise about the order in which several listeners on the same component run, so keep each listener independent. Note too that getActionCommand() defaults to the button text. If the text might be translated into another language, set a stable command with button.setActionCommand("increment") instead.

Actions: one command, many controls

Desktop apps often trigger the same command from several places: a toolbar button, a menu item and a keyboard shortcut. Swing's Action interface bundles the code and its presentation (name, icon, tooltip, accelerator key, enabled state). Give one Action to several components, and they all share it. Disable the action, and every control disables itself:

Java Sharing an Action between a button and a menu item

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

To add a keyboard shortcut, set Action.ACCELERATOR_KEY for menus (KeyStroke.getKeyStroke("control S")) or register the action in a component's input map with key bindings, Swing's preferred replacement for raw KeyListeners:

Java
JComponent root = frame.getRootPane();
root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("control S"), "save");
root.getActionMap().put("save", save);

Reading input and reacting to typing

A JTextField gives you its text with getText(), always as a String. Turning it into a number is your job, and users will type anything: blanks, letters, "21,5" with a comma, a minus sign alone. Parse defensively, catch NumberFormatException, and tell the user what's wrong instead of crashing (see Type Casting and Conversion).

You can react at two moments:

  • On demand: an ActionListener on a Convert button, or on the text field itself (fired when the user presses Enter).
  • As the user types: a DocumentListener on field.getDocument(). Every Swing text component stores its text in a Document model, and the document fires an event on every insert and removal.

Here's the professional approach to the converter: first write the conversion as plain, GUI-free code that you can test, then connect it to Swing. Our server can't measure fonts, so this runnable version uses the text field's model, a PlainDocument, directly; inserting text into it is exactly what happens when a user types into a JTextField.

Java Converter logic wired to Swing models

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Look at the live preview for the blank input: it says "Enter a temperature", not an exception. Replacing the text fires a removeUpdate (when there was text to remove) and then an insertUpdate, so the listener can run twice for one "typed" line; the label always ends up showing the final state. Notice also how little of the code touches Swing. The convert method can be tested with plain JUnit (see Unit Testing), and the GUI just passes text in and shows text out.

The temperature converter app

Here is the full desktop version. It adds a JComboBox to choose the direction, converts when you click the button or press Enter, shows errors in red, and selects the input after each conversion so the next value can be typed straight away. Run it locally with java TemperatureConverter.java.

Java
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import javax.swing.*;

public class TemperatureConverter {
    enum Direction {
        C_TO_F("ยฐC โ†’ ยฐF"), F_TO_C("ยฐF โ†’ ยฐC");
        private final String label;
        Direction(String label) { this.label = label; }
        @Override public String toString() { return label; }
    }

    /** Returns the result text, or throws IllegalArgumentException with a friendly message. */
    static String convert(String input, Direction direction) {
        String text = input.strip().replace(',', '.');
        if (text.isEmpty()) throw new IllegalArgumentException("Enter a temperature");
        double value;
        try {
            value = Double.parseDouble(text);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("'" + input.strip() + "' is not a number");
        }
        return switch (direction) {
            case C_TO_F -> String.format("%.1f ยฐC = %.1f ยฐF", value, value * 9 / 5 + 32);
            case F_TO_C -> String.format("%.1f ยฐF = %.1f ยฐC", value, (value - 32) * 5 / 9);
        };
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TemperatureConverter::createAndShow);
    }

    private static void createAndShow() {
        JTextField input = new JTextField(8);
        JComboBox<Direction> direction = new JComboBox<>(Direction.values());
        JButton convertButton = new JButton("Convert");
        JLabel result = new JLabel("Type a temperature and press Enter", SwingConstants.CENTER);
        Color normal = result.getForeground();

        Runnable doConvert = () -> {
            try {
                result.setText(convert(input.getText(), (Direction) direction.getSelectedItem()));
                result.setForeground(normal);
            } catch (IllegalArgumentException e) {
                result.setText(e.getMessage());
                result.setForeground(Color.RED);
            }
            input.selectAll();
            input.requestFocusInWindow();
        };
        convertButton.addActionListener(e -> doConvert.run());
        input.addActionListener(e -> doConvert.run());          // Enter in the text field
        direction.addActionListener(e -> {                      // re-convert when the direction changes
            if (!input.getText().isBlank()) doConvert.run();
        });

        JPanel controls = new JPanel(new FlowLayout(FlowLayout.CENTER, 8, 8));
        controls.add(input);
        controls.add(direction);
        controls.add(convertButton);

        JPanel content = new JPanel(new BorderLayout(0, 8));
        content.setBorder(BorderFactory.createEmptyBorder(12, 12, 12, 12));
        content.add(controls, BorderLayout.CENTER);
        content.add(result, BorderLayout.SOUTH);

        JFrame frame = new JFrame("Temperature Converter");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

A few details worth copying into your own apps: the enum's toString provides the combo box labels; one Runnable holds the conversion so three listeners can share it; errors are shown in the window instead of a stack trace; and selectAll() plus requestFocusInWindow() make keyboard use pleasant. Dialogs are one line away too: JOptionPane.showMessageDialog(frame, "Saved!") shows a message, and JOptionPane.showConfirmDialog(...) asks yes/no.

Mouse and window events

Two more listeners appear in almost every app. They have several methods, so you extend the adapter classes:

Java
canvas.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() == 2) {
            status.setText("Double-click at " + e.getX() + ", " + e.getY());
        }
    }
});

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent e) {
        int answer = JOptionPane.showConfirmDialog(frame, "Quit without saving?", "Quit",
                JOptionPane.YES_NO_OPTION);
        if (answer == JOptionPane.YES_OPTION) {
            frame.dispose();
        }
    }
});

Long tasks with SwingWorker

Listeners run on the EDT, and while one runs, the window can't repaint or respond (you saw that in the previous lesson). Anything that may take more than about a tenth of a second (reading files, network calls, database queries, heavy calculations) belongs on a background thread. But background threads must not touch Swing components. SwingWorker<T, V> solves both halves:

  • doInBackground() runs on a worker thread and returns the final result of type T. Call publish(V...) from it to send intermediate values.
  • process(List<V>) runs on the EDT with published values, so it may update components. Swing may merge several publish calls into one process call.
  • done() runs on the EDT when the work finishes; call get() there to obtain the result (or the exception thrown in the background).
  • setProgress(0..100) fires a "progress" property change, which is perfect for a JProgressBar. Call execute() to start the worker.

The example counts primes on a worker thread and reports progress after each quarter of the range. While it works, the "user" clicks a button, and the click is handled right away because the EDT is free:

Java SwingWorker keeps the EDT free

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The worker started on a background thread, the other button responded while the calculation was still running, and done() updated the label on the EDT. The progress messages aren't printed one by one because Swing may batch them; process shows only the newest one, which is all a label needs. In a real app you'd also disable the Start button while the worker runs (re-enable it in done()), and you could offer a Cancel button that calls worker.cancel(true); long loops in doInBackground should check isCancelled().

Never call worker.get() on the EDT before the work is finished: it blocks until the result is ready, which freezes the window just like doing the work there. Call it inside done(), where the result is already available. (The demo calls it on the main thread only so the program waits before exiting.)

For repeated, quick UI updates such as a clock or an animation, use javax.swing.Timer instead: new Timer(1000, e -> clock.setText(LocalTime.now().toString())).start(); fires its listener on the EDT every second, so no extra threads are needed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Two buttons share one ActionListener. How can the listener tell which button was clicked?

    Every ActionEvent carries its source component and an action command string (the button text by default, or whatever setActionCommand set).
  2. 2. An Action object is used by a toolbar button and a menu item. What happens when your code calls action.setEnabled(false)?

    Components built from an Action listen to its properties, so changing its enabled state, name or tooltip updates every component that uses it.
  3. 3. Where should a SwingWorker update a JLabel with intermediate progress?

    doInBackground runs on a worker thread and must not touch components. publish() sends values to process(), which Swing calls on the EDT.
  4. 4. Which listener lets you update a preview on every keystroke in a JTextField?

    A text field fires ActionEvents only when Enter is pressed. Its Document fires insertUpdate and removeUpdate on every change.
  5. 5. A user types "abc" into the converter and clicks Convert. The code calls Double.parseDouble without a try/catch. What happens?

    Uncaught exceptions in listeners are printed by the EDT, which keeps running, so the user just sees nothing happen. Catch NumberFormatException and show a helpful message instead.

Summary

  • Components are event sources: register listeners such as ActionListener, ItemListener, ChangeListener and DocumentListener; they run on the EDT.
  • Single-method listeners are functional interfaces, so write them as lambdas or method references; use adapter classes (MouseAdapter, WindowAdapter) for multi-method ones.
  • Use getActionCommand() or getSource() to share listeners, and Action objects to share a command (name, tooltip, shortcut, enabled state) between buttons, menus and key bindings.
  • Text fields return strings: parse defensively, catch NumberFormatException and show errors in the UI; listen to the Document for live updates.
  • Keep logic in plain, testable classes and let the Swing code only pass values in and out.
  • Run slow work in a SwingWorker: doInBackground off the EDT, process and done on it; use javax.swing.Timer for periodic UI updates.

Next: JavaFX Introduction, where you'll meet stages, scenes, layout panes, properties and binding.