• category: swing folder: ToolButtonPopup title: JToggleButtonからポップアップメニューを開く tags: [JToggleButton, JPopupMenu, JToolBar, Icon] author: aterai pubdate: 2006-07-10T10:10:27+09:00 description: クリックするとポップアップメニューを表示するJToggleButtonを作成し、これをツールバーに追加します。 image: https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTVg5xIBaI/AAAAAAAAAnw/ds2ybXI2lUE/s800/ToolButtonPopup.png hreflang:
       href: https://java-swing-tips.blogspot.com/2008/12/adding-jpopupmenu-to-jtoolbar-button.html
       lang: en

概要

クリックするとポップアップメニューを表示するJToggleButtonを作成し、これをツールバーに追加します。

サンプルコード

class MenuArrowIcon implements Icon {
  @Override public void paintIcon(Component c, Graphics g, int x, int y) {
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setPaint(Color.BLACK);
    g2.translate(x, y);
    g2.drawLine(2, 3, 6, 3);
    g2.drawLine(3, 4, 5, 4);
    g2.drawLine(4, 5, 4, 5);
    g2.dispose();
  }

  @Override public int getIconWidth()  {
    return 9;
  }

  @Override public int getIconHeight() {
    return 9;
  }
}

class MenuToggleButton extends JToggleButton {
  private static final Icon i = new MenuArrowIcon();
  protected JPopupMenu pop;
  public MenuToggleButton() {
    this("", null);
  }

  public MenuToggleButton(Icon icon) {
    this("", icon);
  }

  public MenuToggleButton(String text) {
    this(text, null);
  }

  public MenuToggleButton(String text, Icon icon) {
    super();
    Action a = new AbstractAction(text) {
      @Override public void actionPerformed(ActionEvent ae) {
        MenuToggleButton b = (MenuToggleButton) ae.getSource();
        if (pop != null) {
          pop.show(b, 0, b.getHeight());
        }
      }
    };
    a.putValue(Action.SMALL_ICON, icon);
    setAction(a);
    setFocusable(false);
    setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4 + i.getIconWidth()));
  }

  @Override public void setPopupMenu(final JPopupMenu pop) {
    this.pop = pop;
    pop.addPopupMenuListener(new PopupMenuListener() {
      @Override public void popupMenuCanceled(PopupMenuEvent e) {}

      @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) {}

      @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
        setSelected(false);
      }
    });
  }

  @Override protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Dimension dim = getSize();
    Insets ins = getInsets();
    int x = dim.width - ins.right;
    int y = ins.top + (dim.height - ins.top - ins.bottom - i.getIconHeight()) / 2;
    i.paintIcon(this, g, x, y);
  }
}
View in GitHub: Java, Kotlin

解説

  • JToggleButtonの右側に余白を設定してそこに下向きの矢印アイコンを描画
  • JToggleButtonActionListenerを追加しクリックするとJPopupMenu#show(...)メソッドでJPopupMenuを表示
    • JPopupMenuの表示位置はクリック位置ではなくJToggleButtonの下辺になるよう調整

参考リンク

コメント