How do I assign keyboard shortcut to JTabbedPane tabs?

To assign a keyboard shortcut for accessing JTabbedPane‘s tab you can use the setMnemonicAt(int tabIndex, int mnemonic) method of the JTabbedPane class. The tabIndex parameter is a zero-based value parameter which means that the first tab is at index number 0. For the mnenomic parameter you can use constants value defined in the java.awt.event.KeyEvent class.

Here is an example in action on how to assign keyboard shortcut to JTabbedPane‘s tabs. To access the tabs you can use the ALT + A, ALT + B, ALT + C and ALT + D keyboard combination.

package org.kodejava.example.swing;

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

public class TabbedPaneKeyboardShortcut extends JPanel {
    public TabbedPaneKeyboardShortcut() {
        initializeUI();
    }

    private void initializeUI() {
        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(400, 200));

        JTabbedPane pane = new JTabbedPane();
        pane.addTab("A Tab", new JPanel());
        pane.addTab("B Tab", new JPanel());
        pane.addTab("C Tab", new JPanel());
        pane.addTab("D Tab", new JPanel());

        pane.setMnemonicAt(0, KeyEvent.VK_A);
        pane.setMnemonicAt(1, KeyEvent.VK_B);
        pane.setMnemonicAt(2, KeyEvent.VK_C);
        pane.setMnemonicAt(3, KeyEvent.VK_D);

        this.add(pane, BorderLayout.CENTER);
    }

    public static void showFrame() {
        JPanel panel = new TabbedPaneKeyboardShortcut();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTabbedPane Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                TabbedPaneKeyboardShortcut.showFrame();
            }
        });
    }
}
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply