Jack Ng

Essay

Learning Java, Part 16: Swing and JavaFX

Study notes on Swing's components, containers and layout managers, the event dispatch thread, buttons, text fields, check boxes and lists, then JavaFX's stage, scene and node model, its controls and event handling, and how the two compare today. Written entirely by an AI model.

This part covers Schildt’s Chapters 16 and 17, which introduce Java’s two desktop GUI toolkits. CITS2005 is unlikely to examine either. They are still worth a read, because they show inheritance, interfaces, inner classes, lambdas and the event model from Part 15 working together in a real library.

Swing

Swing is in the JDK (javax.swing). It is built on top of the older AWT (java.awt), and its classes start with J: JFrame, JButton, JLabel.

Components and containers

  • A component is a visible element: JLabel, JButton, JTextField, JCheckBox, JList. Every Swing component extends JComponent.
  • A container holds components. The top-level containers are windows: JFrame (a main window) and JDialog. JPanel is a lightweight container used to group components inside a window.
  • A JFrame has several panes; you add components to its content pane, which frame.add(...) does for you.

Layout managers

You don’t usually place components at pixel positions. A layout manager arranges them and rearranges them when the window resizes:

Layout Arranges components
FlowLayout left to right, wrapping like text (default for JPanel)
BorderLayout in five areas: NORTH, SOUTH, EAST, WEST, CENTER (default for JFrame)
GridLayout in a grid of equal cells
BoxLayout in one row or one column
GridBagLayout in a flexible grid with constraints per component

Complex screens nest panels, each with its own layout.

A first Swing program

// compile only: opens a window
import javax.swing.*;
import java.awt.*;

public class TeaTimer {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(TeaTimer::build);   // run on the event dispatch thread
    }

    private static void build() {
        JFrame frame = new JFrame("Tea timer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new FlowLayout());

        JTextField minutes = new JTextField("3", 4);
        JCheckBox milk = new JCheckBox("Milk");
        JButton start = new JButton("Start");
        JLabel status = new JLabel("Ready");

        start.addActionListener(e -> {
            try {
                int m = Integer.parseInt(minutes.getText().strip());
                status.setText("Brewing for " + m + " min" + (milk.isSelected() ? ", with milk" : ""));
            } catch (NumberFormatException ex) {
                status.setText("Enter a whole number");
            }
        });

        frame.add(new JLabel("Minutes:"));
        frame.add(minutes);
        frame.add(milk);
        frame.add(start);
        frame.add(status);
        frame.setSize(420, 100);
        frame.setVisible(true);
    }
}

Line by line:

  • SwingUtilities.invokeLater schedules the GUI’s construction on the event dispatch thread (EDT). Swing is not thread-safe: every change to a component must happen on the EDT. Event handlers already run there.
  • setDefaultCloseOperation(EXIT_ON_CLOSE) ends the program when the window closes. Without it, closing the window only hides it and the program keeps running.
  • addActionListener registers a listener exactly as in Part 15. A lambda works because ActionListener has one method.
  • setVisible(true) comes last, after everything is added.

Long work must not run on the EDT. A handler that downloads a file or sleeps freezes the whole window, because the EDT can’t repaint or respond while it is busy. Use a SwingWorker or another thread (Part 11), then update components through invokeLater.

More components

  • JTextField holds one line of text; getText() and setText() read and change it. Pressing Enter in it fires an ActionEvent. JTextArea holds several lines.
  • JCheckBox toggles on and off; isSelected() reads it, and it fires ItemEvents. JRadioButtons grouped in a ButtonGroup allow one choice from several.
  • JList<E> shows a list of items. Selection changes fire ListSelectionEvents, and getSelectedValue() returns the choice. Wrap it in a JScrollPane to get scroll bars.
  • JOptionPane.showMessageDialog(frame, "Done") shows a quick pop-up.
// compile only: opens a window
import javax.swing.*;

public class Picker {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame("Pick a tea");
            JList<String> list = new JList<>(new String[] {"green", "oolong", "black", "white"});
            JLabel chosen = new JLabel("Nothing yet");
            list.addListSelectionListener(e -> {
                if (!e.getValueIsAdjusting()) chosen.setText("Chosen: " + list.getSelectedValue());
            });
            f.add(new JScrollPane(list), java.awt.BorderLayout.CENTER);
            f.add(chosen, java.awt.BorderLayout.SOUTH);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.pack();                       // size to fit the contents
            f.setVisible(true);
        });
    }
}

getValueIsAdjusting() is true while the mouse button is still down, so the check avoids reacting twice to one click.

JavaFX

JavaFX was designed as Swing’s successor. It used to be bundled with the JDK, but since Java 11 it has been a separate open-source project, OpenJFX, which you add as a library (for example through Maven or Gradle). The examples below therefore need JavaFX installed to run.

Stage, scene and nodes

JavaFX uses a theatre metaphor:

  • A Stage is a window. The first one is supplied by the runtime.
  • A Scene is the content shown on a stage.
  • The scene holds a tree of nodes, called the scene graph. Layout panes (VBox, HBox, BorderPane, GridPane, FlowPane) are nodes that contain other nodes; controls (Label, Button, TextField, CheckBox, ListView) are leaf nodes.

A JavaFX program extends Application, whose lifecycle echoes the applet one: init(), then start(Stage) on the JavaFX application thread, then stop() when it closes. main just calls launch(args).

// not run: needs the OpenJFX library
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class TeaFx extends Application {
    @Override
    public void start(Stage stage) {
        TextField minutes = new TextField("3");
        CheckBox milk = new CheckBox("Milk");
        Label status = new Label("Ready");
        Button start = new Button("Start");

        start.setOnAction(e -> status.setText(
            "Brewing for " + minutes.getText() + " min" + (milk.isSelected() ? ", with milk" : "")));

        VBox root = new VBox(10, minutes, milk, start, status);
        root.setPadding(new Insets(12));
        stage.setScene(new Scene(root, 300, 180));
        stage.setTitle("Tea timer");
        stage.show();
    }

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

The event model is the same as Swing’s: setOnAction registers an EventHandler<ActionEvent>, which is a functional interface. Like Swing, JavaFX is single-threaded: change the scene graph only on the application thread, or through Platform.runLater.

JavaFX also offers things Swing lacks: styling with CSS, layouts defined in an XML format (FXML), properties with bindings (a label can be bound to a text field so it updates automatically), and built-in charts, animation and effects.

Which is used today?

  • Swing is still in every JDK and runs a lot of existing desktop software, including the IntelliJ IDEA IDE.
  • JavaFX is used for newer desktop applications, and it has an active open-source community.
  • Most new user interfaces are web or mobile apps instead. In Java, Android uses its own toolkit, and web front ends are written in JavaScript or TypeScript with Java on the server.

Whatever the toolkit, the skills carry over: components in a tree, layout managers, listeners, and never blocking the UI thread.

Exam-style checks

  • What is the difference between a component and a container? Name a top-level container.
  • Why should Swing components be created and changed only on the event dispatch thread?
  • What goes wrong if an event handler runs a five-second calculation directly?
  • Compare Stage, Scene and node in JavaFX with JFrame, content pane and component in Swing.

Where to practise

Turn the Part 13 word-frequency program into a Swing window: a text area to paste text into, a button, and a JList that shows the top words. Then add a check box that ignores case. If you install OpenJFX, rebuild the same program in JavaFX with a ListView and compare how much code each version needs.