How to link a JMenuItem to a JButton
Question
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)?
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);
OTHER TIPS
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.