• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JToolTipにJButtonのMnemonicを表示
#navi(../)
#tags()
RIGHT:Posted by &author(aterai); at 2010-11-15
*JToolTipにJButtonのMnemonicを表示 [#ic2516e4]
JButtonにMnemonicが設定されている場合、JToolTipにそれを表示します。
---
title: JToolTipにJButtonのMnemonicを表示
tags: [JToolTip, JButton, Mnemonic]
author: aterai
pubdate: 2010-11-15T14:41:06+09:00
description: JButtonにMnemonicが設定されている場合、JToolTipにそれを表示します。
---
* 概要 [#ic2516e4]
`JButton`に`Mnemonic`が設定されている場合、`JToolTip`にそれを表示します。

-&jnlp;
-&jar;
-&zip;
#download(https://lh5.googleusercontent.com/_9Z4BYR88imo/TQTP7StneAI/AAAAAAAAAew/RwPtDfNOEyg/s800/MnemonicToolTip.png)

//#screenshot
#ref(http://lh5.ggpht.com/_9Z4BYR88imo/TQTP7StneAI/AAAAAAAAAew/RwPtDfNOEyg/s800/MnemonicToolTip.png)

**サンプルコード [#t35bb5eb]
* サンプルコード [#t35bb5eb]
#code(link){{
class MnemonicToolTip extends JToolTip {
  private final JLabel mnemonicLabel = new JLabel();
  public MnemonicToolTip() {
    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);
  }
}
}}

**解説 [#gc7f8a7c]
-上
--setToolTipTextで直接Mnemonicを追加
-下
--JToolTipにBorderLayoutを設定して、Mnemonic用のJLabelを追加
* 解説 [#gc7f8a7c]
- 上
-- `setToolTipText`で直接`Mnemonic`を追加
- 下
-- `JToolTip`に`BorderLayout`を設定して、`Mnemonic`用の`JLabel`を追加

**参考リンク [#w7797da0]
-[[JToolTipにアイコンを表示>Swing/ToolTipIcon]]
* 参考リンク [#w7797da0]
- [[JToolTipにアイコンを表示>Swing/ToolTipIcon]]

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