How to create a JButton with a menu?

后端 未结 6 775
一向
一向 2020-12-30 20:16

I want to create a Toolbar in my application. If you click a button on that toolbar, it will pop up a menu, just like in Eclipse\'s toolbar. I don\'t know how to do this in

6条回答
  •  清歌不尽
    2020-12-30 20:39

    I don't see why this is harder than it needs to be or why you should use a MouseListener. The solution by Steve McLeod works, but where the menu appears depends on where the mouse was clicked. Why not just use an ActionListener as normally used for a JButton. It seems neither harder nor less hard.

    final JPopupMenu menu = new JPopupMenu();
    menu.add(...whatever...);
    
    final JButton button = new JButton();
    button.setText("My Menu");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ev) {
            menu.show(button, button.getBounds().x, button.getBounds().y
               + button.getBounds().height);
        }
    });
    

    This positions the menu about the same as a menu in a JMenuBar for me, and the position is consistent. You could place it differently by modifying the x and y in menu.show().

提交回复
热议问题