如何使JMenu在JMenuBar中具有Button行为

时间:2010-03-16 17:08:00

标签: java swing jmenubar jmenu

我试图让JMenu表现得像JButton,但我遇到了一些问题,希望有人可以提供帮助!

我已经用这个添加了一个MenuListener到JMenu项目,但我不能让弹出菜单/焦点离开,让我能够正确点击JMenu重复次数来触发这个功能,我希望有人可以告诉我我是什么做错了。感谢。

public void menuSelected(MenuEvent e)
        {
            ... // do stuff here code
            JMenu source = (JMenu)e.getSource();
            source.setSelected(false);
            source.setPopupMenuVisible(false);

        }

5 个答案:

答案 0 :(得分:8)

不完全确定你在问什么...

JMenuBar继承自Container - 如果您要为JButton添加JMenu,而不是JMenuBar menuBar = .... JButton myButton = .... menuBar.add(myButton); ,您只需致电 -

{{1}}

答案 1 :(得分:1)

此代码示例在eclipse中运行,再次关注您如何使用它?

public class MyMenuFrame extends JFrame {


    public MyMenuFrame() throws HeadlessException {
        super("My Frame");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(400, 300);
        Container pane = this.getContentPane();
        pane.setLayout(new BorderLayout());
        pane.add(new JLabel("Hi there"), BorderLayout.PAGE_START);
        this.setVisible(true);
        JMenuBar menubar = new JMenuBar();
        JMenu menu = new JMenu("File");

        menu.addMenuListener(new MenuListener() {

            @Override
            public void menuSelected(MenuEvent e) {
                System.out.println("a");

            }

            @Override
            public void menuDeselected(MenuEvent e) {
                System.out.println("a");

            }

            @Override
            public void menuCanceled(MenuEvent e) {
                System.out.println("a");

            }
        });
        menubar.add(menu);
        this.setJMenuBar(menubar );
    }

    public static void main(String[] args) {
        new MyMenuFrame();
    }
}

答案 2 :(得分:1)

我知道这是一个老线程,但我想我可能有一个解决方案。我在我的一个应用程序中偶然发现了这个问题,并找到了解决方法。尝试使用JMenuItem而不是JMenu。当您将它附加到JMenuBar时,它将具有与JMenu相同的L& F.您唯一要做的就是设置新“按钮”的大小,因为布局管理器(即使您没有设置)也会根据自己的规则调整此组件的大小:

http://www.javaworld.com/javaworld/jw-09-2000/jw-0922-javatraps.html

在该链接下找到了这样做的方法(如果你觉得点击链接感到不舒服,谷歌的“setsize不起作用” - 它将是前10名的结果)。如果没有正确设置尺寸,新的“按钮”将填满JMenuBar的剩余空间。

试试这段代码:

menuItem.setMinimumSize(someMenu.getSize());
menuItem.setPreferredSize(someMenu.getSize());
menuItem.setMaximumSize(someMenu.getSize());
menuItem.setActionCommand("ActionText");

setActionCommand()方法将设置一个动作命令,这样当您单击新的“按钮”时,这将是动作事件参数传递给动作执行方法的动作命令,以便您可以轻松识别它: / p>

public void actionPerformed(ActionEvent e) {
    System.out.println(e.getActionCommand());
}

希望这有帮助!

答案 3 :(得分:0)

很难确定你在这里要做什么。但我认为你没有正确使用JMenu。

JMenu是表示菜单的对象。它与菜单栏(JMenuBar)和菜单项(JMenuItem)分开。 JMenuBar通常包含多个JMenus(文件,编辑等),而JMenus又包含多个JMenuItems(New,Open,Close)。 JMenuItems是单击的菜单中的“按钮”。

要使菜单项像按钮一样,只需将其添加到菜单中即可。例如:

JMenu fileMenu = new JMenu("File");
JMenuItem newChoice = new JMenuItem("New");
newChoice.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        newHasBeenSelected();
    }
});
fileMenu.add(newChoice);

如果您正在尝试创建弹出菜单,则需要使用JPopupMenu而不是JMenu,并且您不需要JMenuBar。以下是菜单上的Java教程:http://java.sun.com/docs/books/tutorial/uiswing/components/menu.html

以下是JMenuBarJMenuJPopupMenuJMenuItem的Java文档。

如果您编辑问题并对您正在做的事情做出更详细的解释,我可能会提供更具体的帮助。

答案 4 :(得分:0)

好的我决定对此进行更多调查,以下是reslut,看起来像JButton一样,但在jmenubar上看起来就像是一个jmenu。代码如下。 (注意只是将一个actionListener添加到JMenu没有正常工作,这就是mouselistener的原因。你就像普通按钮一样向menubutton添加一个actionListener,只要你不向menubutton添加任何menuitems(技术上你可以)它将在JMenuBar上显示为JMenu,但其行为类似于按钮。

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.lang.reflect.Method;
import java.util.EventListener;   
import javax.swing.ImageIcon;
import javax.swing.JMenu;

public class MenuButton extends JMenu {

private boolean startedIn = false;
private ActionListener action;

public MenuButton(String title) {
    super(title);
    removeListeners(this);
    this.addMouseListener(new MenuButtonListener());

}

public MenuButton(ImageIcon icon) {
    super();
    removeListeners(this);
    this.addMouseListener(new MenuButtonListener());
    this.setIcon(icon);
}

public void addActionListener(ActionListener a) {
    action = a;
}
    //we need to remove all the listeners already associated with a JMenu. If we do
//not do this, then it will not behave as expected because some mouseclicks are eaten 
//by these listeners. There is no easy way to do that, the following method is a 
//workaroundprovided in the java bug database. 
static private void removeListeners(Component comp) {
    Method[] methods = comp.getClass().getMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        String name = method.getName();
        if (name.startsWith("remove") && name.endsWith("Listener")) {

            Class[] params = method.getParameterTypes();
            if (params.length == 1) {
                EventListener[] listeners = null;
                try {
                    listeners = comp.getListeners(params[0]);
                } catch (Exception e) {
                    // It is possible that someone could create a listener
                    // that doesn't extend from EventListener. If so, ignore
                    // it
                    System.out.println("Listener " + params[0]
                            + " does not extend EventListener");
                    continue;
                }
                for (int j = 0; j < listeners.length; j++) {
                    try {
                        method.invoke(comp, new Object[] { listeners[j] });
                        // System.out.println("removed Listener " + name +
                        // " for comp " + comp + "\n");
                    } catch (Exception e) {
                        System.out
                                .println("Cannot invoke removeListener method "
                                        + e);
                        // Continue on. The reason for removing all
                        // listeners is to
                        // make sure that we don't have a listener holding
                        // on to something
                        // which will keep it from being garbage collected.
                        // We want to
                        // continue freeing listeners to make sure we can
                        // free as much
                        // memory has possible
                    }
                }
            } else {
                // The only Listener method that I know of that has more
                // than
                // one argument is removePropertyChangeListener. If it is
                // something other than that, flag it and move on.
                if (!name.equals("removePropertyChangeListener"))
                    System.out.println("    Wrong number of Args " + name);
            }
        }
    }
}

public class MenuButtonListener extends MouseAdapter {

    boolean within = false;
    boolean pressed = false;


    public void mousePressed(MouseEvent e) {
        MenuButton.this.setSelected(true);
        pressed = true;
        //System.out.println("pressed");
    }

    public void mouseReleased(MouseEvent e) {
        //System.out.println("released");
        MenuButton.this.setSelected(false);
        if (action != null && within && pressed) {
            action.actionPerformed(new ActionEvent(this,
                    ActionEvent.ACTION_PERFORMED, null));
            MenuButton.this.setSelected(false);
        }
        pressed = false;
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        within = true;
    }

    @Override
    public void mouseExited(MouseEvent e) {
        within = false;
    }
}
}