• 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

概要

JButtonMnemonicが設定されている場合、JToolTipにそれを表示します。

サンプルコード

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

解説

    • setToolTipTextで直接Mnemonicを追加
    • JToolTipBorderLayoutを設定して、Mnemonic用のJLabelを追加

参考リンク

コメント