How to link a JMenuItem to a JButton

exit, java, jbutton, jmenuitem, swing

Solution

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);

Problem

Let's say I have a JMenuItem with a text inside "Exit", and a JButton with the text "Exit", the command which JButton will use is System.exit(0), of course using Action Listener, Ok i Know, I can put the same codes when clicking on the JMenuItem, but isn't there a way, that when I click on the JMenuItem, the JButton is clicked so then the following commands are executed (JButton commands)?

Original source