Custom JMenuItems in Java

2019-02-05 00:26发布

问题:

Would it be possible to create a custom JMenuItem that contains buttons? For example would it be possible to create a JMenuITem with an item similar to this:

+----------------------------------------+
| JMenuItem [ Button | Button | Button ] |
+----------------------------------------+

回答1:

I doubt there is an easy way to do this. You can do something like:

JMenuItem item = new JMenuItem("Edit                       ");
item.setLayout( new FlowLayout(FlowLayout.RIGHT, 5, 0) );
JButton copy = new JButton("Copy");
copy.setMargin(new Insets(0, 2, 0, 2) );
item.add( copy );
menu.add( item );

But there are several problems:

a) the menu doesn't close when you click on the button. So that code would need to be added to your ActionListener

b) the menu item doesn't respond to key events like the left/right arrow, so there is no way to place focus on the button using the keyboard. This would involve UI changes to the menu item and I have no idea where to start for this.

I would just use the standard UI design an create sub menus.



回答2:

I'm sure there is, Like personally I would use individual menuitems and just put them side by side and have an action listener for each individual button. The tricky part would be putting them inside a container like a JPanel and putting them in a flow layout or a Grid layout



回答3:

Old question, but you can do this fairly easily with a JToolBar...

    //Make a popup menu with one menu item
    final JPopupMenu popupMenu = new JPopupMenu();
    JMenuItem menuItem = new JMenuItem();

    //The panel contains the custom buttons
    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
    panel.setAlignmentX(Component.LEFT_ALIGNMENT);       
    panel.add(Box.createHorizontalGlue());        
    JToolBar toolBar = new JToolBar();
    JButton toolBarButton = new JButton();
    toolBarButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            popupMenu.setVisible(false); //hide the popup menu
            //other actions
        }
    });
    toolBar.setFloatable(false);
    toolBar.add(toolBarButton);
    panel.add(toolBar);

    //Put it all together        
    menuItem.add(panel);        
    menuItem.setPreferredSize(new Dimension(menuItem.getPreferredSize().width, panel.getPreferredSize().height)); //do this if your buttons are tall
    popupMenu.add(menuItem);