• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:JToggleButtonからポップアップメニューを開く
#navi(../)
*JToggleButtonからポップアップメニューを開く [#e15ce510]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2006-07-10~
更新日:&lastmod;

#contents

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

#screenshot

**サンプルコード [#o01c8911]
#code{{
 class MenuToggleButton extends JToggleButton {
   private final Icon i = new MenuArrowIcon();
   private final String space;
   public MenuToggleButton(final AbstractAction aa, String space) {
     super(new AbstractAction((String)aa.getValue("Name")+space) {
       public void actionPerformed(ActionEvent ae) {
         aa.actionPerformed(ae);
       }
     });
     this.space = space;
   public MenuToggleButton(final AbstractAction aa) {
     super(aa);
     this.setFocusPainted(false);
     this.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4+i.getIconWidth()));
   }
   public void paintComponent(Graphics g) {
     super.paintComponent(g);
     Dimension dim = getSize();
     Insets ins = getInsets();
     int h = dim.height;
     int w = SwingUtilities.computeStringWidth(g.getFontMetrics(), space);
     int x = dim.width-ins.right-i.getIconWidth()-(w-i.getIconWidth())/2;
     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);
   }
 }

}}
-&jnlp;
-&jar;
-&zip;

**解説 [#i6f6caf9]
上記のサンプルでは、ボタンの文字列に空白文字を追加することで右側にスペースを取得し、ここに下向きの矢印を上書きしています。
上記のサンプルでは、JToggleButtonの右側に余白を設定して、そこに下向きの矢印を上書きしています。

**参考リンク [#f95e2567]
-[[XP Style Icons - Windows Application Icon, Software XP Icons>http://www.icongalore.com/]]
--アイコンを利用しています。
-[[Swing bug? cannot set width of JToggleButton>http://forum.java.sun.com/thread.jspa?threadID=791450]]

**コメント [#h4a49a4d]
#comment