是否有可能创建一个包含按钮的自定义JMenuItem
?例如,是否可以创建一个类似于以下项目的JMenuItem
:
+----------------------------------------+
| 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 );
我相信有这样的方法,就像我个人会使用单独的菜单项并将它们并排放置,并为每个按钮设置一个动作监听器。棘手的部分是将它们放入容器中,例如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);