Simulate JMenuItem MouseListener on JButton

63 views Asked by At

I don't know if title is understandable. Whatever, I have some JMenuItems, and for these I've set up mouseListener.

mntmExtractPaleographyFeature.addMouseListener(this);

where mntmExtractPaleographyFeature is a JMenuitem and this is the class that implements MouseListener.

So I've added method for mouseListener like

@Override
public void mouseReleased(MouseEvent arg0) {
    if(arg0.getSource()==mntmExtractPaleographyFeature) {
        //Code Here
    }

Now I have this JButton extractPaleographyB that does exact the same thing of the JMenuItem. I don't want to copy/paste code two times (also because It's not the only button/jmenuitem). I've tried with

extractPaleographyB.addMouseListener(mntmExtractPaleographyFeature.getMouseListeners()[1]);

but it doesn't work. Any idea?

1

There are 1 answers

7
StanislavL On

Create an Action and use for both menu item and button

The piece of code from the tutorial

Action leftAction = new LeftAction(); //LeftAction code is shown later
...
button = new JButton(leftAction)
...
menuItem = new JMenuItem(leftAction);

To create an Action object, you generally create a subclass of AbstractAction and then instantiate it. In your subclass, you must implement the actionPerformed method to react appropriately when the action event occurs. Here's an example of creating and instantiating an AbstractAction subclass:

leftAction = new LeftAction("Go left", anIcon,
             "This is the left button.",
             new Integer(KeyEvent.VK_L));
...
class LeftAction extends AbstractAction {
    public LeftAction(String text, ImageIcon icon,
                      String desc, Integer mnemonic) {
        super(text, icon);
        putValue(SHORT_DESCRIPTION, desc);
        putValue(MNEMONIC_KEY, mnemonic);
    }
    public void actionPerformed(ActionEvent e) {
        displayResult("Action for first button/menu item", e);
    }
}