简体   繁体   English

如何将JMenuItem链接到JButton

[英]How to link a JMenuItem to a JButton

假设我有一个带有“Exit”内部文本的JMenuItem,以及带有文本“Exit”的JButton,JButton将使用的命令是System.exit(0),当然使用Action Listener,Ok i Know,I can在单击JMenuItem时输入相同的代码,但是没有办法,当我单击JMenuItem时,单击JButton然后执行以下命令(JButton命令)?

What you can do is create an Action object, and use that for both your JButton and your JMenuItem . 你可以做的是创建一个Action对象,并将它用于你的JButton和你的JMenuItem

Action exit = new AbstractAction() {
        private static final long serialVersionUID = -2581717261367873054L;

        @Override
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    };
exit.putValue(Action.NAME, "Exit");
exit.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_X);

JButton exitButton = new JButton(exit);
JMenuItem exitItem = new JMenuItem(exit);

A good way to do this is to set the same ActionListener to both components. 执行此操作的一种好方法是将两个组件设置为相同的ActionListener Like this: 像这样:

JButton button = new JButton ("Exit");
JMenuItem item = new JMenuItem ("Exit");

ActionListener exitaction = new ActionListener ()
{
    public void actionPerformed (ActionEvent e)
    {
        System.exit (0);
    }
};

button.addActionListener (exitaction);
item.addActionListener (exitaction);

However, I would recommend against using System.exit (0) . 但是,我建议不要使用System.exit (0) The better way of closing the program (which I assume is basically a JFrame ) is by setting 关闭程序的更好方法(我假设基本上是一个JFrame )是通过设置

frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE)

(where frame is the window of the program) frame是程序的窗口)

and calling frame.dispose () in the ActionListener . 并在ActionListener调用frame.dispose ()

I consider the best way to do this is to register the same ActionListener instance in the event listeners of both JMenuItem and JButton, it's like using the old Command design pattern. 我认为最好的方法是在JMenuItem和JButton的事件监听器中注册相同的ActionListener实例,就像使用旧的Command设计模式一样。

I would not recommend trying to trick the events 'engine' like making the JMenuItem fire the event related to the pressing of the JButton, since that is not what's happening but what you seem to want is to reuse both actions to 2 distinct events. 我不建议尝试欺骗事件'引擎',就像让JMenuItem触发与按下JButton相关的事件一样,因为那不是正在发生的事情,但你似乎想要的是将两个动作重用于2个不同的事件。

You can try to save the button as a class field 您可以尝试将按钮保存为类字段

private JButton button;

and insert in the click event handler of the menu item the code 并在菜单项的click事件处理程序中插入代码

button.doClick();

but the solution of SoboLAN is more elegant. SoboLAN的解决方案更优雅。

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

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