简体   繁体   中英

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 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. 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) . The better way of closing the program (which I assume is basically a JFrame ) is by setting

frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE)

(where frame is the window of the program)

and calling frame.dispose () in the ActionListener .

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.

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.

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

button.doClick();

but the solution of SoboLAN is more elegant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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