• category: swing folder: TabMnemonic title: JTabbedPaneのタブにMnemonicを追加 tags: [JTabbedPane, Mnemonic, JLabel] author: aterai pubdate: 2008-09-01T13:22:20+09:00 description: JTabbedPaneのタブにMnemonicを追加します。 image: https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTUu2fjTpI/AAAAAAAAAmg/EST6gnFRH84/s800/TabMnemonic.png

概要

JTabbedPaneのタブにMnemonicを追加します。

サンプルコード

tab.addTab("Button", new JButton("button"));
tab.setMnemonicAt(3, KeyEvent.VK_B);
tab.setDisplayedMnemonicIndexAt(3, 0);
View in GitHub: Java, Kotlin

解説

上記のサンプルコードは、例えばタブタイトルの先頭文字がBのタブにAlt+Bでフォーカスが移動するように、JTabbedPane#setMnemonicAt(...)メソッドを使用してMnemonicを設定しています。 また、タブタイトルの先頭文字(B)にアンダーラインが入るようにJTabbedPane#setDisplayedMnemonicIndexAt(...)メソッドで設定しています。


  • JDK 6以降でタブにJComponentを追加する場合、JTabbedPane#setDisplayedMnemonicIndexAt(...)メソッドではMnemonicにアンダーラインは引かれないので、追加するコンポーネント側でアンダーラインを引くよう設定する
    int index = tab.getTabCount();
    String tabTitle = "label(0)";
    JPanel p = new JPanel(new BorderLayout());
    JLabel label = new JLabel(tabTitle);
    JButton button = new JButton("x");
    p.add(label,  BorderLayout.WEST);
    p.add(button, BorderLayout.EAST);
    tab.addTab(tabTitle, new JTree());
    tab.setTabComponentAt(index, p);
    tab.setMnemonicAt(index, KeyEvent.VK_0);
    label.setDisplayedMnemonic(KeyEvent.VK_0);
    

参考リンク

コメント