Java中的自定义JMenuItems

13

是否有可能创建一个包含按钮的自定义JMenuItem?例如,是否可以创建一个类似于以下项目的JMenuItem

Google Chrome的自定义和控制菜单屏幕截图,其中编辑菜单项被圈出

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

该图片链接打开了一个空白页面。 - kleopatra
3个回答

4

我怀疑没有简单的方法来做到这一点。您可以尝试以下方式:

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 );

但是有几个问题:
a) 当您单击按钮时,菜单不会关闭。因此,需要在ActionListener中添加代码。
b) 菜单项不响应左/右箭头等按键事件,因此无法使用键盘将焦点放在按钮上。这将涉及到对菜单项的UI更改,我不知道从哪里开始。
我只是使用标准UI设计并创建子菜单。

1

我相信有这样的方法,就像我个人会使用单独的菜单项并将它们并排放置,并为每个按钮设置一个动作监听器。棘手的部分是将它们放入容器中,例如JPanel,并将它们放入流布局或网格布局中。


1

虽然这是一个老问题,但你可以很容易地通过使用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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接