简体   繁体   English

单击JMenuItem时执行动作?

[英]Performing an action when an JMenuItem is clicked?

So i have made a simple program with a basic menu at the top of the frame, Now i just need to put actions behind each JMenuItem. 所以我做了一个简单的程序,在框架顶部有一个基本菜单,现在我只需要在每个JMenuItem后面放置操作即可。 Im struggling to work the code out though, Here is what i thought would work: 我正在努力编写代码,这是我认为可以的:

JMenu file_Menu = new JMenu("File");
JMenuItem fileExit = new JMenuItem("Exit Program"); 
file_Menu.add(fileExit);
fileExit.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
        JFrame hello = new JFrame("POPUP");
        hello.setSize(100,75);
        hello.setDefaultCloseOperation(hello.EXIT_ON_CLOSE);
        hello.setVisible(true);
    }
});
main_Menu.add(file_Menu);

This doesn't seem to work though, I thought that this code would create a small popup window when the menu item is clicked. 但是,这似乎不起作用,我认为当单击菜单项时,此代码将创建一个小的弹出窗口。

Can any spot the bug because i cant seem to. 可以发现任何错误,因为我似乎无法。

Suggestion: Instead of adding a separate ActionListener , just use AbstractAction : 建议:不用添加单独的ActionListener ,只需使用AbstractAction

JMenuItem fileExit = new JMenuItem(new AbstractAction("Exit Program") {
    public void actionPerformed(ActionEvent ae) {
        JFrame hello = new JFrame("POPUP");
        hello.setSize(100,75);
        hello.setDefaultCloseOperation(hello.EXIT_ON_CLOSE);
        hello.setVisible(true);
    }
});

I'd also suggest, instead of setting EXIT_ON_CLOSE on the popup menu, you set it on the main frame of your application, and have the action simply call theMainFrame.dispose() . 我还建议,不要在弹出菜单上设置EXIT_ON_CLOSE ,而是将其设置在应用程序的主框架上,然后使操作简单地调用theMainFrame.dispose()

You got it working, but you have another problem. 您可以正常使用,但是还有另一个问题。

Don't do this: 不要这样做:

hello.setDefaultCloseOperation(hello.EXIT_ON_CLOSE);

When you close the pop-up frame, your entire JVM terminates. 关闭弹出框时,整个JVM终止。 Consult JFrame.setDefaultCloseOperation javadocs for a more appropriate value. 有关更合适的值,请查阅JFrame.setDefaultCloseOperation javadocs。

给Action的一个实例(从AbstractAction扩展)给JMenuItem

Based on the code you posted it looks like it should work, but we can't see the entire context of how the menu item is being used. 根据您发布的代码,它看起来应该可以工作,但是我们无法看到菜单项使用方式的整个上下文。

Did you debug your code (with a System.out.println) to see if the ActionListener is being invoked? 您是否调试了代码(使用System.out.println)以查看是否正在调用ActionListener?

If you need more help post your SSCCE that demonstrates the problem. 如果您需要更多帮助,请发布SSCCE来演示问题。

Fixed it. 修复。

Forgot to add the actionPerformed method. 忘记添加actionPerformed方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM