Java中的自定义项
是否可以创建包含按钮的自定义Java中的自定义项,java,swing,jmenu,jmenuitem,Java,Swing,Jmenu,Jmenuitem,是否可以创建包含按钮的自定义JMenuItem?例如,是否可以创建一个JMenuITem,其中的项目类似于: +----------------------------------------+ | JMenuItem [ Button | Button | Button ] | +----------------------------------------+ 我相信有,就像我个人一样,我会使用单个菜单项,将它们并排放置,并为每个按钮设置一个动作侦听器。棘手的部分是将它们放在一个容器(如
JMenuItem
?例如,是否可以创建一个JMenuITem
,其中的项目类似于:
+----------------------------------------+
| JMenuItem [ Button | Button | Button ] |
+----------------------------------------+
我相信有,就像我个人一样,我会使用单个菜单项,将它们并排放置,并为每个按钮设置一个动作侦听器。棘手的部分是将它们放在一个容器(如JPanel)中,然后将它们放在一个流布局或网格布局中,我怀疑是否有一种简单的方法可以做到这一点。您可以执行以下操作:
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设计来创建子菜单。这个老问题,但是你可以用一个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);
指向图像的链接将打开一个空白页