Ok I have a JButton that opens a new frame/window and I also have MenuItem that needs to call the same action as well. I am stuck it works one way and not the other. Below is my code and thanks in advance! - Scott
Now my button1 action listener which works fine.
This works. Now I would like to call this same action from a JMenu Item. Now I know how to make the menu and add menu items. How ever the actionListener code will not execute. My menu code is blow in case I did something wrong.
Thanks for the help! So to re-iterate my question. The JButton and JMenuItem need to call the same Action Listener.
both a JButton and a JMenuItem take an Action as parameter in the constructor. You can get such an Action by subclassing an AbstractAction, where you have to override the actionPerformed method.
You can set properties, like icons and other properties, with the method action.putValue(...), and you can enable/disable your button and menu item in one go by using the setEnabled method. It does take some practise to make a good use of an Action, in my experience. See the API.
Another way, in which you only share the actionListener, is to code
There are three kinds of actuaries: those who can count, and those who can't.
Scott Eric Catalano wrote:So to re-iterate my question. The JButton and JMenuItem need to call the same Action Listener.
You can do something like this:Then they will both invoke the same listener no matter where you place them.
However that's probably not the way I would do it. I would usually create an instantiation of javax.swing.Action and pass it to the JButton and JMenuItem constructors:This is slightly more work but can be cleaner. (ActionExample)
Thanks for all the suggestions! What would I need to change to make this work based on the code I provided above? The btn1.addActionListener contains my action code which works with the button..does not work with the menu item. One frame has the button code and another frame has the menu code.