---
category: swing
folder: MnemonicToolTip
title: JToolTipにJButtonのMnemonicを表示
tags: [JToolTip, JButton, Mnemonic]
author: aterai
pubdate: 2010-11-15T14:41:06+09:00
description: JButtonにMnemonicが設定されている場合、JToolTipにそれを表示します。
image: https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTP7StneAI/AAAAAAAAAew/RwPtDfNOEyg/s800/MnemonicToolTip.png
---
* Summary [#summary]
`JButton`に`Mnemonic`が設定されている場合、`JToolTip`にそれを表示します。
#download(https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTP7StneAI/AAAAAAAAAew/RwPtDfNOEyg/s800/MnemonicToolTip.png)
* Source Code Examples [#sourcecode]
#code(link){{
class MnemonicToolTip extends JToolTip {
private final JLabel mnemonicLabel = new JLabel();
public MnemonicToolTip() {
super();
setLayout(new BorderLayout());
mnemonicLabel.setForeground(Color.GRAY);
mnemonicLabel.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 2));
add(mnemonicLabel, BorderLayout.EAST);
}
@Override public Dimension getPreferredSize() {
Dimension d = super.getPreferredSize();
if (mnemonicLabel.isVisible()) {
d.width += mnemonicLabel.getPreferredSize().width;
}
return d;
}
@Override public void setComponent(JComponent c) {
if (c instanceof AbstractButton) {
AbstractButton b = (AbstractButton) c;
int mnemonic = b.getMnemonic();
if (mnemonic > 0) {
mnemonicLabel.setVisible(true);
mnemonicLabel.setText("Alt + " + KeyEvent.getKeyText(mnemonic));
} else {
mnemonicLabel.setVisible(false);
}
}
super.setComponent(c);
}
}
}}
* Description [#explanation]
* Description [#description]
- 上
-- `JButton`に`PropertyChangeListener`を設定して`Mnemonic`が変更されたら`JButton#setToolTipText(...)`メソッドで直接`Mnemonic`を変更
- 下
-- `JToolTip`に`BorderLayout`を設定して`Mnemonic`用の`JLabel`を表示する`JToolTip`を作成して`JButton`に設定
* Reference [#reference]
- [[JToolTipにアイコンを表示>Swing/ToolTipIcon]]
* Comment [#comment]
#comment
#comment