Custom JMenuItems in Java

2019-02-04 23:37发布

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:

screenshot of Google Chrome's customize and control menu with the edit menu item circled

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

3条回答
Rolldiameter
2楼-- · 2019-02-05 00:20

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.

查看更多
可以哭但决不认输i
3楼-- · 2019-02-05 00:36

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);
查看更多
干净又极端
4楼-- · 2019-02-05 00:37

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

查看更多
登录 后发表回答