Swing/MnemonicToolTip のバックアップ(No.6)
- バックアップ一覧
 - 差分 を表示
 - 現在との差分 を表示
 - 現在との差分 - Visual を表示
 - ソース を表示
 - Swing/MnemonicToolTip へ行く。
  
- 1 (2012-12-25 (火) 05:09:15)
 - 2 (2014-12-12 (金) 15:23:18)
 - 3 (2016-03-11 (金) 15:44:44)
 - 4 (2017-07-25 (火) 14:49:41)
 - 5 (2018-07-25 (水) 18:42:42)
 - 6 (2020-07-31 (金) 19:58:57)
 - 7 (2021-12-26 (日) 07:52:49)
 - 8 (2025-01-03 (金) 08:57:02)
 - 9 (2025-01-03 (金) 09:01:23)
 - 10 (2025-01-03 (金) 09:02:38)
 - 11 (2025-01-03 (金) 09:03:21)
 - 12 (2025-01-03 (金) 09:04:02)
 - 13 (2025-06-19 (木) 12:41:37)
 - 14 (2025-06-19 (木) 12:43:47)
 
 
- 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: 

 
概要
JButtonにMnemonicが設定されている場合、JToolTipにそれを表示します。
Screenshot

Advertisement
サンプルコード
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);
  }
}
View in GitHub: Java, Kotlin解説
- 上
JButtonにPropertyChangeListenerを設定し、Mnemonicが変更されたらJButton#setToolTipText(...)メソッドで直接Mnemonicを変更
 - 下
JToolTipにBorderLayoutを設定して、Mnemonic用のJLabelを表示するJToolTipを作成してJButtonに設定