TITLE:JTabbedPaneのタブにMnemonicを追加

Posted by at 2008-09-01

JTabbedPaneのタブにMnemonicを追加

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

  • &jnlp;
  • &jar;
  • &zip;
TabMnemonic.png

サンプルコード

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

解説

上記のサンプルコードは、三番目のタブに`Alt+Bでフォーカスが移動するように、JTabbedPane#setMnemonicAt`メソッドを使用しています。 また、タブタイトルの先頭文字(`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);

コメント