0

can i call actionperformed method with jmenu using swing

i am using the following code

     JMenu menu1= new JMenu("File");
     MenuBar mb= new MenuBar();
      mb.add(menu1);
      set JmenuBar(mb)
     menu1.addActionListener(this);


  public void actionPerformed(ActionEvent ae)
  {

      JOptionPane.showMessaageDialog(null,"menu clicked");
     // but its not working


      }

thanks in Advance

ADESH RAJPUT
  • 131
  • 1
  • 5
  • 10

1 Answers1

3

The action a JMenu is designed to perform is to open a popup with JMenuItems, it doesn't support doing anything else (and even if it did, it would confuse your users). Custom actions are supposed to be handled by JMenuItems in the popup. Install them with something like:

JMenu menu ..
Action myAction = new AbstractAction("Do XY") {
    public void actionPerformed(..) {
        // implement doing XY
    } 
};
menu.add(myAction);  
kleopatra
  • 51,061
  • 28
  • 99
  • 211
  • What if the use case requires a JMenu to react like a JMenuItem ? – James P. Nov 18 '15 at 20:26
  • @JamesPoulson wondering: why would you have such a non-standard requirement? Can't be done, at least not without a very deep-down (in the plaf classes, I would guess, didn't try, though) tweak. – kleopatra Nov 19 '15 at 11:50
  • Requirements can be weird and the client is king. A contact said he was asked to put only a top JMenu instead of having a single JMenuItem added to it. He ended up using a MouseAdapter and mousePressed. – James P. Nov 24 '15 at 04:36