Java › Swing

Add keyboard navigation to custom Swing components

Use Swing key bindings to open a filter, select a restaurant, and switch tabs. Draw a focus ring so users can see which control will receive the next key.

Add keyboard navigation to custom Swing components

In my restaurant app, I wanted to get from the search field to a detail tab using the keyboard. I bound the keys to the controls that use them and added a focus ring so you can see where the next key will go.

The examples use Java 17 and come from the Restaurant Information System (RSIS).

Start with a job you can finish without a mouse

Start in the search field, choose a district, open a result, then move to a different tab in the detail view. Tab and Shift+Tab move between controls. The arrows and Enter act on whichever control has focus.

Focused controlKeysResult
District filter chipEnter or DownOpen the menu
Results listUp, Down, or EnterSelect a row or open its detail view
Detail tab barLeft, Right, Home, or EndSelect the neighboring, first, or last tab

When I open the district filter, the popup menu highlights the current option. The arrows start moving from that option. The results list uses the arrow bindings from JList and adds Enter to open the selected restaurant. I draw the detail tabs as a single control, so the tab bar handles arrow presses by changing the selected index. RSIS filter chip · Popup selection path

Bind a key to an action at the right scope

The InputMap maps a keystroke to an action name, and the ActionMap maps that name to an Action. On the district chip, Enter and Down both map to open. A test can call that action directly on the event dispatch thread (EDT) without sending a desktop keypress.

I use WHEN_FOCUSED for keys that belong to one widget. The filter’s binding stays out of the way when the arrows move the caret in the search field or Enter activates another button. Swing can also look for bindings on ancestor containers and in the focused window. Bind actions shared by a group of controls to their parent, and register a window-wide shortcut once to avoid collisions. I keep the bindings that Swing already provides and add the action the app needs. Oracle’s Swing key binding tutorial

Save the Java 17 example as ListKeys.java and run java ListKeys.java in a desktop session. Tab from the text field to the list, use the arrows to choose a row, and press Enter. The status label shows which restaurant you opened.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;

class ListKeys {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            var list = new JList<>(new String[]{"Spring Cafe", "Riverside Grill"});
            var status = new JLabel("Choose a restaurant to open");
            list.getAccessibleContext().setAccessibleName("Restaurant search results");
            list.getInputMap(JComponent.WHEN_FOCUSED)
                    .put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "open");
            list.getActionMap().put("open", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent event) {
                    String selected = list.getSelectedValue();
                    if (selected != null) {
                        status.setText("Opened " + selected);
                    }
                }
            });

            var frame = new JFrame("Keyboard restaurant search");
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            var search = new JTextField();
            search.getAccessibleContext().setAccessibleName("Search by restaurant name");
            frame.add(search, BorderLayout.NORTH);
            frame.add(new JScrollPane(list), BorderLayout.CENTER);
            frame.add(status, BorderLayout.SOUTH);
            frame.setSize(360, 220);
            frame.setVisible(true);
        });
    }
}

In RSIS, Enter and a double-click call the same method to open the selected restaurant. Pressing Enter with an empty selection leaves the screen as it is. RSIS list key binding and callback

Draw selection and focus as separate states

With Reviews selected, press Tab to move to another button. The app still shows the reviews, and the Reviews tab stays selected. Its focus ring disappears because the next keystroke goes to the button.

The tab bar repaints when it gains or loses focus. Its paint method checks isFocusOwner() before drawing the ring. If you click a tab and switch back to the keyboard, the ring still tells you whether the tab bar has focus. RSIS tab bar focus handling

The tab bar exposes the PAGE_TAB_LIST role. I put the selected tab’s name and position in its accessible name. The filter chip includes the filter name and its current value. A test can inspect those properties. To hear how they’re announced, run the app with a screen reader on the target desktop. RSIS accessible tab name and role

The district filter menu with its first choice focused after an Enter key press Figure 1. Pressing Enter opens the district choices in the running Swing window.

A focus ring on the RSIS Reviews tab after pressing the right arrow Figure 2. After Enter opens the details, the right arrow selects Reviews with the tab bar focused.

Check the action in a test and the focus path on a desktop

In a headless test I can select a known restaurant, invoke the open action, and check the callback. The existing RSIS test uses this approach. It covers the decision about which restaurant to open. A desktop run covers the rest of the path, including popup navigation and how the visible focus moves between components. RSIS component test

1
./gradlew test --tests 'org.example.rsis.ui.components.ComponentsTest.restaurantListSelectsByIdAndOpensOnEnter'

For the desktop check, start at the search field and use Tab to reach a filter. Open it with Enter, move with the arrows, and select a value. Reopen the menu and dismiss it with Escape. Then Tab to the results and open a row. In the detail view, Tab to the tab bar and use the arrows to switch tabs. Watch where the focus ring goes when the menu closes and when the detail screen opens.

  • Tab and Shift+Tab move through the controls in both directions.
  • The filter opens, accepts a choice, and closes on Escape.
  • The results open the selected restaurant and the detail arrows switch tabs.
  • Focus is visible as it moves, and selected styling remains after focus leaves.
This post is licensed under CC BY 4.0 by the author.