【问题标题】:Custom JMenuItems in JavaJava 中的自定义 JMenuItem
【发布时间】:2011-05-12 01:23:30
【问题描述】:

是否可以创建包含按钮的自定义JMenuItem?例如,是否可以使用类似于以下的项目创建 JMenuITem

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

【问题讨论】:

  • 图片链接打开一个空白页面

标签: java swing jmenu jmenuitem


【解决方案1】:

我怀疑是否有一种简单的方法可以做到这一点。您可以执行以下操作:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多