Event Handling in Swing: Listeners, Adapters and Actions
How Swing programs react to the user: event sources, listener interfaces and event objects, handling button clicks with classes and lambdas, adapter classes and window events, Action objects shared by buttons and menus, and key bindings through input maps and action maps.
kvi5hnuCode Sprout team member12 min readOn this page
A GUI program spends most of its life waiting. The operating system watches the keyboard and mouse and reports what happens; the program decides what, if anything, to do about each report. This article covers how Swing delivers those reports: the event delegation model with its sources, listeners and event objects; the many ways of writing listeners; adapter classes; and Action objects with key bindings, which let a button, a menu item and a keystroke share one command.
Sources, listeners and events

The AWT event model has three roles:
- An event source is a component that can report something: a button is clicked, a window is closed, the mouse moves. It keeps a list of listeners and has methods to register them, such as
addActionListener. - A listener is an object whose class implements a listener interface, such as
ActionListenerwith its single methodactionPerformed(ActionEvent). - An event object describes what happened. All event classes derive from
java.util.EventObject, whosegetSource()returns the source.ActionEvent,WindowEvent,MouseEventandKeyEventadd their own details.
When the user acts, the event goes into the AWT event queue, the event dispatch thread takes it out and hands it to the component, and the component calls the matching method on every registered listener, passing an event object. A source can have any number of listeners, and one listener can listen to several sources. Different sources produce different event types: a button produces action events, a window produces window events.
Because listeners run on the EDT, they must finish quickly. A listener that blocks (on a network call, a big file, a long calculation) freezes the whole user interface until it returns. Hand such work to a background thread.
Handling a button click
Buttons are created with a label, an icon or both:
var yellowButton = new JButton("Yellow");
var blueButton = new JButton(new ImageIcon("blue-ball.png"));
var helpButton = new JButton("<html><b>Help</b> me</html>"); // labels may use simple HTML
panel.add(yellowButton);
To react to clicks, register an ActionListener. Suppose three buttons should change a panel's background color. One approach is a listener class whose objects remember their color:
class ColorListener implements ActionListener {
private final JPanel panel;
private final Color color;
ColorListener(JPanel panel, Color color) { this.panel = panel; this.color = color; }
public void actionPerformed(ActionEvent event) {
panel.setBackground(color);
}
}
yellowButton.addActionListener(new ColorListener(panel, Color.YELLOW));
The listener needs access to the panel, here through a constructor parameter. Making ColorListener an inner class of the frame would let it reach the frame's panel field directly.
Listeners as lambdas
ActionListener has a single abstract method, so it is a functional interface, and most listeners today are lambdas:
exitButton.addActionListener(_ -> System.exit(0));
The _ is an unnamed variable (Java 22) for the event parameter you do not need; in older code you see event or e. For several related buttons, a helper method avoids repetition. Each call creates a new listener object that captures the method's parameters:
void makeButton(String name, Color color) {
var button = new JButton(name);
buttonPanel.add(button);
button.addActionListener(_ -> buttonPanel.setBackground(color));
}
...
makeButton("Yellow", Color.YELLOW);
makeButton("Blue", Color.BLUE);
No listener class, fields or constructor are needed: the captured color plays the role of the field. Older programs use anonymous inner classes (new ActionListener() { public void actionPerformed(...) {...} }) for the same purpose; lambdas are shorter and clearer. Method references work too: button.addActionListener(this::save) if save takes an ActionEvent.
What the event tells you
ActionEvent offers getSource() (the component), getActionCommand() (by default the button's label; set your own with setActionCommand, so that translations and label changes do not break your code), getModifiers() (which modifier keys were held), and getWhen() (a timestamp). One listener shared by several buttons can use these to tell them apart, although a separate lambda per button is usually clearer.
removeActionListener unregisters a listener and getActionListeners() lists them. If several listeners are registered, all are called, but the specification does not promise an order. (Swing's buttons currently call the most recently added one first, as the demo shows.) Do not write listeners that depend on running before or after each other.
Adapter classes
Some listener interfaces have many methods. WindowListener has seven:
public interface WindowListener extends EventListener {
void windowOpened(WindowEvent e);
void windowClosing(WindowEvent e);
void windowClosed(WindowEvent e);
void windowIconified(WindowEvent e);
void windowDeiconified(WindowEvent e);
void windowActivated(WindowEvent e);
void windowDeactivated(WindowEvent e);
}
windowClosing is called when the user asks to close the window (the window closes only if something then hides or disposes it); windowClosed comes after it has been disposed; "iconified" means minimized; a window is "activated" when it becomes the foreground window that receives keyboard input. Two further interfaces report maximize/restore (WindowStateListener) and focus changes (WindowFocusListener).
Usually you care about one of these methods, and writing six empty ones is tedious. For most AWT listener interfaces with more than one method, there is an adapter class that implements all of them with empty bodies: WindowAdapter, MouseAdapter, KeyAdapter, ComponentAdapter, FocusAdapter and so on. Extend the adapter and override what you need. A common use asks for confirmation before closing:
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent e) {
if (JOptionPane.showConfirmDialog(frame, "Really quit?", "Quit",
JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
frame.dispose();
}
});
WindowAdapter implements all three window listener interfaces at once. If Swing were designed today, these interfaces would simply have default methods; the adapters predate default methods by many years. Interfaces with several methods cannot be implemented by lambdas, so an anonymous subclass of the adapter, as above, is the usual idiom.
Actions
The same command is often reachable in several ways: a toolbar button, a menu item, and a keyboard shortcut. You could attach one listener to all of them, but Swing offers something better, the Action interface. An action is an ActionListener that also carries the command's description and state:
actionPerformed(ActionEvent), inherited fromActionListener;setEnabled(boolean)andisEnabled();putValue(key, value)andgetValue(key)for properties such as the display name and icon;addPropertyChangeListenerandremovePropertyChangeListener, through which buttons and menu items track the action's properties.
Buttons, menu items and toolbar buttons constructed from an action take their text, icon and tooltip from it and register it as their listener. More importantly, they stay in sync: disable the action and every control using it is grayed out; rename it and every label changes.
Predefined property keys:
| Key | Meaning |
|---|---|
NAME | Text shown on buttons and menu items. |
SMALL_ICON, LARGE_ICON_KEY | Icons for menu items and buttons (toolbar buttons use the large one if present). |
SHORT_DESCRIPTION | Tooltip text. |
LONG_DESCRIPTION | Longer help text; not used by Swing components. |
MNEMONIC_KEY, DISPLAYED_MNEMONIC_INDEX_KEY | Underlined mnemonic letter and its position. |
ACCELERATOR_KEY | Keystroke shown next to a menu item and triggering it. |
ACTION_COMMAND_KEY | The action command of the generated events. |
SELECTED_KEY | Selected state for toggle buttons and check box menu items. |
AbstractAction implements everything except actionPerformed, storing the key/value pairs and managing the property change listeners. Extend it and add the command:
class ColorAction extends AbstractAction {
private final JComponent target;
ColorAction(String name, Icon icon, Color color, JComponent target) {
super(name, icon);
putValue(SHORT_DESCRIPTION, "Set panel color to " + name.toLowerCase());
putValue("color", color);
this.target = target;
}
public void actionPerformed(ActionEvent event) {
target.setBackground((Color) getValue("color"));
}
}
var blueAction = new ColorAction("Blue", blueIcon, Color.BLUE, panel);
panel.add(new JButton(blueAction)); // text, icon, tooltip and listener in one step
Article 96 adds the same actions to menus and toolbars.
Key bindings
To trigger an action from the keyboard, you need to know which component receives keystrokes. At any time one component has the keyboard focus, usually marked visually (a button with focus has a thin border in the default look and feel). Tab moves the focus; Space clicks a focused button. But a shortcut such as Ctrl+B should work no matter which component has focus. Swing solves this with key bindings.
Every JComponent has three input maps, consulted under different conditions:
| Condition | When the map is used |
|---|---|
WHEN_FOCUSED | The component itself has the keyboard focus. |
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT | The component contains the component that has focus. |
WHEN_IN_FOCUSED_WINDOW | The component is anywhere in the window that has focus. |
A key press is processed in this order: first the focused component's WHEN_FOCUSED map; then the WHEN_ANCESTOR_OF_FOCUSED_COMPONENT maps of its parents, going outwards; finally the WHEN_IN_FOCUSED_WINDOW maps of all visible, enabled components in the window. The first binding to an enabled action wins.
An input map does not point to actions directly. It maps a KeyStroke to an arbitrary key (usually a string), and a separate action map maps that key to an Action. The indirection lets several input maps share actions and lets look-and-feels supply their own bindings:
InputMap imap = panel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");
ActionMap amap = panel.getActionMap();
amap.put("panel.blue", blueAction);
KeyStroke.getKeyStroke parses descriptions such as "ctrl B", "shift F5", "alt shift X", "released ENTER" or "typed a": modifiers (shift, ctrl, control, meta, alt, altGraph), then pressed (the default), released or typed, then a key name matching a KeyEvent.VK_ constant. Bind a key to the conventional name "none", which has no action, to disable a binding that a look-and-feel or an outer component would otherwise provide.
Use stable, invented strings such as "panel.blue" as action map keys, not the displayed action names: those can change with every redesign or translation.
On macOS, users expect Cmd instead of Ctrl for shortcuts. Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx() returns the right modifier for the platform; build KeyStroke.getKeyStroke(KeyEvent.VK_B, mask) with it.
A complete program that combines actions, buttons, key bindings and a confirm-on-close window listener:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ColorButtons {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
var frame = new JFrame("Color Buttons");
var panel = new JPanel();
panel.setPreferredSize(new Dimension(360, 160));
// One Action per command: used by a button and by a keystroke
Action yellow = colorAction("Yellow", Color.YELLOW, panel);
Action blue = colorAction("Blue", Color.BLUE, panel);
Action red = colorAction("Red", Color.RED, panel);
for (Action a : new Action[] {yellow, blue, red}) panel.add(new JButton(a));
InputMap imap = panel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
ActionMap amap = panel.getActionMap();
imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");
imap.put(KeyStroke.getKeyStroke("ctrl R"), "panel.red");
amap.put("panel.yellow", yellow);
amap.put("panel.blue", blue);
amap.put("panel.red", red);
// Ask before closing: we handle windowClosing ourselves
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent e) {
int answer = JOptionPane.showConfirmDialog(frame, "Really quit?", "Quit",
JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION) {
frame.dispose(); // last window gone: the program ends
}
}
});
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
});
}
static Action colorAction(String name, Color color, JComponent target) {
var action = new AbstractAction(name) {
private static final long serialVersionUID = 1L;
@Override public void actionPerformed(ActionEvent e) {
target.setBackground(color);
}
};
action.putValue(Action.SHORT_DESCRIPTION, "Set the background to " + name.toLowerCase());
return action;
}
}
The program
The demo builds buttons, actions and key bindings without a window, in headless mode, and drives them on the EDT. doClick() simulates a user click, and SwingUtilities.processKeyBindings runs a synthetic key event through the binding lookup exactly as a real key press would be processed. It shows a listener class, a lambda from a helper method, several listeners on one button, listener interfaces and adapters, an Action shared by its button (including enabling and renaming), and key bindings that go through the panel's input and action maps while a button inside it "has the focus".
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.lang.reflect.Method;
import java.util.*;
import java.util.List;
import javax.swing.*;
public class Solution {
static final Map<Color, String> NAMES = Map.of(Color.YELLOW, "yellow", Color.BLUE, "blue", Color.RED, "red",
Color.WHITE, "white", Color.GREEN, "green");
static String name(Color c) { return NAMES.getOrDefault(c, c.toString()); }
/** A named listener class: one object per color. */
static class ColorListener implements ActionListener {
private final JPanel panel;
private final Color color;
ColorListener(JPanel panel, Color color) { this.panel = panel; this.color = color; }
@Override public void actionPerformed(ActionEvent e) {
panel.setBackground(color);
System.out.println(" ColorListener: command \"" + e.getActionCommand() + "\" from "
+ ((JButton) e.getSource()).getText() + " -> " + name(color));
}
}
/** An Action bundles the command with its name, icon, tooltip and enabled state. */
static class ColorAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private final JPanel panel;
ColorAction(String label, Color color, JPanel panel) {
super(label, swatch(color));
putValue(SHORT_DESCRIPTION, "Set panel color to " + label.toLowerCase());
putValue("color", color);
this.panel = panel;
}
@Override public void actionPerformed(ActionEvent e) {
var c = (Color) getValue("color");
panel.setBackground(c);
System.out.println(" ColorAction " + getValue(NAME) + " -> " + name(c));
}
}
static Icon swatch(Color c) {
var img = new BufferedImage(12, 12, BufferedImage.TYPE_INT_RGB);
Graphics2D g = img.createGraphics();
g.setColor(c);
g.fillRect(0, 0, 12, 12);
g.dispose();
return new ImageIcon(img);
}
static void pressKey(JComponent focused, String keyStroke) {
KeyStroke ks = KeyStroke.getKeyStroke(keyStroke);
var e = new KeyEvent(focused, KeyEvent.KEY_PRESSED, 0L, ks.getModifiers(), ks.getKeyCode(), KeyEvent.CHAR_UNDEFINED);
boolean handled = SwingUtilities.processKeyBindings(e);
System.out.println(" key " + ks + " handled: " + handled);
}
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "true");
EventQueue.invokeAndWait(Solution::run); // all Swing work on the EDT
}
static void run() {
var panel = new JPanel();
panel.setBackground(Color.WHITE);
System.out.println("== One listener class, three objects ==");
var yellow = new JButton("Yellow");
var blue = new JButton("Blue");
yellow.addActionListener(new ColorListener(panel, Color.YELLOW));
blue.addActionListener(new ColorListener(panel, Color.BLUE));
panel.add(yellow);
panel.add(blue);
yellow.doClick(); // simulates a user click
blue.doClick();
System.out.println("panel is now " + name(panel.getBackground()));
System.out.println("\n== Lambdas and a helper method ==");
makeButton(panel, "Red", Color.RED).doClick();
System.out.println("panel is now " + name(panel.getBackground()));
System.out.println("\n== Several listeners on one source ==");
var save = new JButton("Save");
save.setActionCommand("file.save"); // decouples the command from the label
ActionListener log = e -> System.out.println(" log: " + e.getActionCommand());
ActionListener backup = e -> System.out.println(" backup: " + e.getActionCommand());
save.addActionListener(log);
save.addActionListener(backup);
save.doClick();
System.out.println("registered: " + save.getActionListeners().length + " (notification order is not specified)");
save.removeActionListener(backup);
save.doClick();
System.out.println("\n== Adapter classes ==");
for (Class<?> c : List.of(WindowListener.class, MouseListener.class, KeyListener.class, ActionListener.class)) {
List<String> methods = Arrays.stream(c.getDeclaredMethods()).map(Method::getName).sorted().toList();
System.out.println(c.getSimpleName() + " (" + methods.size() + "): " + methods);
}
System.out.println("WindowAdapter implements " + Arrays.stream(WindowAdapter.class.getInterfaces())
.map(Class::getSimpleName).sorted().toList());
panel.setSize(300, 120);
panel.addComponentListener(new ComponentAdapter() { // override only what you need
@Override public void componentResized(ComponentEvent e) {
System.out.println(" resized to " + e.getComponent().getWidth() + "x" + e.getComponent().getHeight());
}
});
panel.dispatchEvent(new ComponentEvent(panel, ComponentEvent.COMPONENT_RESIZED));
System.out.println("\n== Actions ==");
var greenAction = new ColorAction("Green", Color.GREEN, panel);
var greenButton = new JButton(greenAction);
panel.add(greenButton);
System.out.println("button text \"" + greenButton.getText() + "\", tooltip \"" + greenButton.getToolTipText()
+ "\", has icon: " + (greenButton.getIcon() != null));
greenButton.doClick();
greenAction.setEnabled(false); // every control using the action follows
System.out.println("action disabled -> button enabled: " + greenButton.isEnabled());
greenButton.doClick();
System.out.println("click on disabled button changed nothing: panel is " + name(panel.getBackground()));
greenAction.setEnabled(true);
greenAction.putValue(Action.NAME, "Lime");
System.out.println("renamed action -> button text: " + greenButton.getText());
System.out.println("\n== Key bindings: input map + action map ==");
var yellowAction = new ColorAction("Yellow", Color.YELLOW, panel);
var blueAction = new ColorAction("Blue", Color.BLUE, panel);
InputMap imap = panel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
imap.put(KeyStroke.getKeyStroke("ctrl Y"), "panel.yellow");
imap.put(KeyStroke.getKeyStroke("ctrl B"), "panel.blue");
imap.put(KeyStroke.getKeyStroke("ctrl G"), "none"); // explicitly does nothing
ActionMap amap = panel.getActionMap();
amap.put("panel.yellow", yellowAction);
amap.put("panel.blue", blueAction);
System.out.println("the focused component is a button inside the panel");
pressKey(yellow, "ctrl Y");
pressKey(yellow, "ctrl B");
pressKey(yellow, "ctrl G");
System.out.println("panel is now " + name(panel.getBackground()));
System.out.println("KeyStroke.getKeyStroke(\"ctrl shift F5\") = " + KeyStroke.getKeyStroke("ctrl shift F5"));
}
static JButton makeButton(JPanel panel, String label, Color color) {
var button = new JButton(label);
panel.add(button);
button.addActionListener(_ -> { // the lambda captures panel and color
panel.setBackground(color);
System.out.println(" lambda -> " + name(color));
});
return button;
}
}
== One listener class, three objects ==
ColorListener: command "Yellow" from Yellow -> yellow
ColorListener: command "Blue" from Blue -> blue
panel is now blue
== Lambdas and a helper method ==
lambda -> red
panel is now red
== Several listeners on one source ==
backup: file.save
log: file.save
registered: 2 (notification order is not specified)
log: file.save
== Adapter classes ==
WindowListener (7): [windowActivated, windowClosed, windowClosing, windowDeactivated, windowDeiconified, windowIconified, windowOpened]
MouseListener (5): [mouseClicked, mouseEntered, mouseExited, mousePressed, mouseReleased]
KeyListener (3): [keyPressed, keyReleased, keyTyped]
ActionListener (1): [actionPerformed]
WindowAdapter implements [WindowFocusListener, WindowListener, WindowStateListener]
resized to 300x120
== Actions ==
button text "Green", tooltip "Set panel color to green", has icon: true
ColorAction Green -> green
action disabled -> button enabled: false
click on disabled button changed nothing: panel is green
renamed action -> button text: Lime
== Key bindings: input map + action map ==
the focused component is a button inside the panel
ColorAction Yellow -> yellow
key ctrl pressed Y handled: true
ColorAction Blue -> blue
key ctrl pressed B handled: true
key ctrl pressed G handled: false
panel is now blue
KeyStroke.getKeyStroke("ctrl shift F5") = shift ctrl pressed F5
Points to notice:
getActionCommand()returned the label for the color buttons and"file.save"where an explicit command was set.- Disabling the action disabled its button, so
doClick()did nothing; renaming the action relabeled the button. Neither required touching the button. - Ctrl+G was not handled: its binding points to
"none", which has no action, so processing continues as if the key were unbound.
Common questions
Lambda or inner class for listeners?
Lambdas for single-method listeners like ActionListener. For multi-method interfaces, extend the adapter class in an anonymous class, or write a named class when the listener has state or is reused.
Why doesn't my KeyListener receive keys?
The component doesn't have the keyboard focus, or isn't focusable (setFocusable(true) and requestFocusInWindow()). For shortcuts, use key bindings with WHEN_IN_FOCUSED_WINDOW or WHEN_ANCESTOR_OF_FOCUSED_COMPONENT instead; they don't depend on focus.
How do I make Enter trigger the default button in a dialog?
rootPane.setDefaultButton(okButton). For Escape to close the dialog, bind KeyStroke.getKeyStroke("ESCAPE") in the root pane's WHEN_IN_FOCUSED_WINDOW map to a close action.
My listener runs a long task and the UI freezes. What do I do?
Start the work in a SwingWorker (or a virtual thread) from the listener, disable the controls if needed, and update the UI in done() or through invokeLater. Never sleep or block inside a listener.
Can I remove a listener I added as a lambda?
Only if you kept a reference to the same lambda object: ActionListener l = e -> ...; button.addActionListener(l); ... button.removeActionListener(l);. Writing the lambda again creates a different object.
API reference
| Class / method | Purpose |
|---|---|
JButton(String), JButton(Icon), JButton(String, Icon), JButton(Action) | Create buttons. |
addActionListener, removeActionListener, getActionListeners, setActionCommand, doClick | Button events. |
ActionListener.actionPerformed(ActionEvent) | React to an action. |
EventObject.getSource(), ActionEvent.getActionCommand(), getModifiers(), getWhen() | Event details. |
WindowListener (7 methods), WindowStateListener, WindowFocusListener, WindowAdapter | Window events. |
MouseAdapter, KeyAdapter, ComponentAdapter, FocusAdapter | Other adapters. |
Action, AbstractAction(name [, icon]), putValue, getValue, setEnabled | Shareable commands. |
Action.NAME, SMALL_ICON, LARGE_ICON_KEY, SHORT_DESCRIPTION, MNEMONIC_KEY, ACCELERATOR_KEY, SELECTED_KEY | Action properties. |
JComponent.getInputMap(condition), getActionMap() | Key bindings. |
WHEN_FOCUSED, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_IN_FOCUSED_WINDOW | Input map conditions. |
KeyStroke.getKeyStroke("ctrl B"), getKeyStroke(keyCode, modifiers) | Describe keys. |
Toolkit.getMenuShortcutKeyMaskEx() | Ctrl or Cmd, depending on the platform. |
Summary
- Sources report events to registered listeners on the event dispatch thread; event objects describe what happened. Keep listeners fast.
- Write listeners as lambdas (helper methods for families of similar buttons) or as classes when they hold more state. Set action commands rather than relying on labels; do not rely on listener order.
- For multi-method listener interfaces, extend the matching adapter class and override only what you need, for example
windowClosingwithDO_NOTHING_ON_CLOSEto confirm before exit. - An
Actionbundles a command with its name, icons, tooltip, shortcut and enabled state; controls built from it stay in sync. - Key bindings connect keystrokes to actions through a component's input map (three focus conditions) and action map, using stable string keys.
Practice Questions
1. A listener for a "Download" button fetches a 200 MB file in actionPerformed. What does the user experience, and why?
The whole window freezes until the download ends: buttons do not respond, and the window may not even repaint when uncovered. actionPerformed runs on the event dispatch thread, the same thread that handles all input and painting, so nothing else can happen until it returns. Start the download on a background thread (for example with SwingWorker) and update the UI from the EDT when it finishes.
2. Why is it better to call setActionCommand("file.save") than to compare getActionCommand() with the button text "Save"?
By default the action command is the button's label. Labels change with redesigns and are translated for other languages, so comparisons against them break silently. An explicit, stable command string separates the program logic from the displayed text.
3. Why can't you add a WindowListener with a lambda, and what is the idiom instead?
A lambda can implement only a functional interface, one with a single abstract method. WindowListener has seven abstract methods. Extend WindowAdapter, which supplies empty implementations of all of them, in an anonymous class and override only the method you need, such as windowClosing.
4. A toolbar button, a menu item and Ctrl+S all save the document. When there is nothing to save, all three should be disabled. How do Actions make this easy?
Create one Action for saving and construct the toolbar button and the menu item from it; bind Ctrl+S to it through an input map and action map (or the menu item's accelerator). Controls built from an action listen to its property changes, so a single saveAction.setEnabled(false) grays out the button and the menu item, and key bindings skip disabled actions.
5. You put a Ctrl+B binding into a panel's WHEN_FOCUSED input map, but pressing Ctrl+B while a button inside the panel has focus does nothing. Why?
The WHEN_FOCUSED map is consulted only when the panel itself has the keyboard focus. Here a child button has the focus, so the button's WHEN_FOCUSED map is checked, then the WHEN_ANCESTOR_OF_FOCUSED_COMPONENT maps of its parents. Put the binding in the panel's WHEN_ANCESTOR_OF_FOCUSED_COMPONENT map (or WHEN_IN_FOCUSED_WINDOW for window-wide shortcuts).
Previous: Drawing with Java 2D: Shapes, Colors, Fonts and Images
Related reading
- Drawing with Java 2D: Shapes, Colors, Fonts and Images
- Java GUI Toolkits and Your First JFrame: AWT, Swing and JavaFX
- Public Key Encryption in Java: RSA, Hybrid Encryption and ML-KEM
- Symmetric Encryption in Java: AES-GCM, Key Generation and Cipher Streams
- Certificates in Java: keytool, Certificate Chains and Signing JAR Files

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.