Custom JMenuItems in Java
Asked Answered
W

3

13

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 ] |
+----------------------------------------+
Winebaum answered 12/5, 2011 at 1:23 Comment(1)
the link to the image opens a blank pageDickson
R
4

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.

Resigned answered 12/5, 2011 at 2:1 Comment(0)
F
1

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

Frivolity answered 12/5, 2011 at 1:38 Comment(0)
E
1

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);
Edwin answered 15/5, 2015 at 15:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.