MyMenuButton类(自己做的按钮)
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPopupMenu; import javax.swing.JToggleButton; import javax.swing.SwingConstants; public class MyMenuButton extends JToggleButton{ private JPopupMenu menu; private static int i=0; public MyMenuButton(){ super(); this.setText("▲"); this.setHorizontalTextPosition(SwingConstants.RIGHT ); addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { if(isSelected()){ setText("▼"); menu.show(MyMenuButton.this, 0, MyMenuButton.this.getHeight()); }else{ setText("▲"); menu.setVisible(false); } } }); } public MyMenuButton(final String label){ super(label); this.setText("▲ "+label); this.setHorizontalTextPosition(SwingConstants.RIGHT ); addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { if(isSelected()){ setText("▼"+label); menu.show(MyMenuButton.this, 0, MyMenuButton.this.getHeight()); }else{ setText("▲"+label); menu.setVisible(false); } } }); } public void addMenu(JPopupMenu menu){ this.menu=menu; } }
Test类(测试类)
import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JPopupMenu; public class Test extends JFrame{//测试类 public Test(){ JPanel p=new JPanel(); //创建弹出菜单 JPopupMenu menu=new JPopupMenu(); menu.add("第一个菜单项"); menu.add("第二个菜单项"); menu.add("第三个个菜单项"); menu.add("第四个菜单项"); MyMenuButton button=new MyMenuButton();//创建按钮 MyMenuButton button2=new MyMenuButton("按钮菜单"); //把建好的菜单放到按钮上 button.addMenu(menu); button2.addMenu(menu); p.add(button); p.add(button2); this.add(p); this.setSize(300, 200); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.setVisible(true); } public static void main(String[] args) { new Test(); } }
结果如图:
注释:可以根据需求进行修改。