---
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
---
* 概要 [#summary]
`JTabbedPane`のタブに`Mnemonic`を追加します。

#download(https://lh3.googleusercontent.com/_9Z4BYR88imo/TQTUu2fjTpI/AAAAAAAAAmg/EST6gnFRH84/s800/TabMnemonic.png)

* サンプルコード [#sourcecode]
#code(link){{
tab.addTab("Button", new JButton("button"));
tab.setMnemonicAt(3, KeyEvent.VK_B);
tab.setDisplayedMnemonicIndexAt(3, 0);
}}

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

----
- `JDK 6`以降でタブに`JComponent`を追加する場合、`JTabbedPane#setDisplayedMnemonicIndexAt(...)`メソッドでは`Mnemonic`にアンダーラインは引かれないので、追加するコンポーネント側でアンダーラインを引くよう設定する
#code{{
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);
}}

* 参考リンク [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JTabbedPane.html#setMnemonicAt-int-int- JTabbedPane#setMnemonicAt(...) (Java Platform SE 8)]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JTabbedPane.html#setDisplayedMnemonicIndexAt-int-int- JTabbedPane#setDisplayedMnemonicIndexAt(...) (Java Platform SE 8)]

* コメント [#comment]
#comment
#comment