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(500, 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(WindowConstants.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();
            }
        });
    }
}

The output of the code snippet above is:

JTabbedPane Tabs with Keyboard Shortcut

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you đŸ™‚.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.