Java中的自定义JMenuItems

是否可以创建包含按钮的自定义JMenuItem ? 例如,是否可以使用与JMenuITem项创建JMenuITem

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

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

我怀疑有一个简单的方法来做到这一点。 你可以这样做:

 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设计创建子菜单。

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

老问题,但你可以用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);