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() {

    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();

        JFrame frame = new JFrame("JTabbedPane Demo");

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA.

Leave a Reply

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