单击JMenuItem时执行操作? [英] Performing an action when an JMenuItem is clicked?

查看:248
本文介绍了单击JMenuItem时执行操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在框架的顶部创建了一个带有基本菜单的简单程序,现在我只需要在每个JMenuItem后面放置动作。我努力工作代码,这是我认为可行的:

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. 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.

推荐答案

建议:不要添加单独的 ActionListener ,只需使用 AbstractAction

Suggestion: Instead of adding a separate ActionListener, just use 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);
    }
});

我还建议,而不是设置 EXIT_ON_CLOSE 在弹出菜单上,将其设置在应用程序的主框架上,然后让操作只需调用 theMainFrame.dispose()

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().

这篇关于单击JMenuItem时执行操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆