概要

クリックするとポップアップメニューを表示する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();
  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()));
  }
  protected JPopupMenu pop;
  @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 all

解説

上記のサンプルでは、JToggleButtonの右側に余白を設定して、そこに下向きの矢印を上書きしています。

参考リンク

コメント