• category: swing folder: LayoutCompoundLabel title: JLabelのアイコンとテキストのどちらにマウスカーソルがあるかを調査する tags: [JLabel, JToolTip, Icon, JMenuItem] author: aterai pubdate: 2020-03-02T18:44:05+09:00 description: JLabelのアイコンとテキストのどちらの上にマウスカーソルが存在するかでツールチップの表示内容を変更します。 image: https://drive.google.com/uc?id=1abUKg4L5olw6cF_cly2Pbg9-tXkkWuth

概要

JLabelのアイコンとテキストのどちらの上にマウスカーソルが存在するかでツールチップの表示内容を変更します。

サンプルコード

Icon icon = UIManager.getIcon("OptionPane.informationIcon");
JLabel label = new JLabel("OptionPane.informationIcon", icon, SwingConstants.LEADING) {
  private final Rectangle viewRect = new Rectangle();
  private final Rectangle iconRect = new Rectangle();
  private final Rectangle textRect = new Rectangle();

  @Override public String getToolTipText(MouseEvent e) {
    SwingUtilities.calculateInnerArea(this, viewRect);
    SwingUtilities.layoutCompoundLabel(
        this,
        this.getFontMetrics(this.getFont()),
        this.getText(),
        this.getIcon(),
        this.getVerticalAlignment(),
        this.getHorizontalAlignment(),
        this.getVerticalTextPosition(),
        this.getHorizontalTextPosition(),
        viewRect,
        iconRect,
        textRect,
        this.getIconTextGap());
    String tip = super.getToolTipText(e);
    if (tip == null) {
      return null;
    } else if (iconRect.contains(e.getPoint())) {
      return "Icon: " + tip;
    } else if (textRect.contains(e.getPoint())) {
      return "Text: " + tip;
    } else {
      return "Border: " + tip;
    }
  }
};
label.setOpaque(true);
label.setBackground(Color.GREEN);
label.setBorder(BorderFactory.createMatteBorder(20, 10, 50, 30, Color.RED));
label.setToolTipText("ToolTipText ToolTipText");
View in GitHub: Java, Kotlin

解説

  • SwingUtilities.calculateInnerArea(...)メソッドでコンポーネントからBorderの余白を除去した矩形領域を取得
  • SwingUtilities.layoutCompoundLabel(...)メソッドで上記の矩形領域を基準にアイコン領域、テキスト領域を計算し、引数で取得
    • 戻り値はクリップされた文字列になるが、上記のサンプルでは未使用
  • JLabelだけではなくJMenuItemなどでもSwingUtilities.layoutCompoundLabel(...)メソッドでアイコン領域、テキスト領域を取得可能

参考リンク

コメント