Question

I just began using JMenu. To ease into it, I decided to use Netbeans form design tool, which has worked great for all components in this app.

Clicking a top-level menu item works great.

For one menu item, I made a submenu with 3 items, each with a mouse click listener.

Here's relevant code for one of the 3 submenus:

  private JMenuItem mnuEditDicAddAllScratch;

  mnuEditDicAddAllScratch = new JMenuItem();


  private void mnuEditDicAddAllScratchMouseClicked(MouseEvent evt) {                                                     

    new WordsToAdd();  // never happened
  } 

    mnuEditDicAddAllScratch.addMouseListener(new MouseAdapter() {

      public void mouseClicked(MouseEvent evt) {

        mnuEditDicAddAllScratchMouseClicked(evt);
      }
    });

    mnuEdit.add(mnuEditDicAddAllScratch);

It didn't work. Clicks ignored.

So I tried an Action listener:

  private void mnuEditDicAddAllScratchActionPerformed(ActionEvent evt) {

    new WordsToAdd();   // WORKED
  }  

mnuEditDicAddAllScratch.addActionListener(new java.awt.event.ActionListener() {

  public void actionPerformed(java.awt.event.ActionEvent evt) {

    mnuEditDicAddAllScratchActionPerformed(evt);
  }
});

And it worked.

So a question is, "Why didn't mouse click listener listen?"

Also, "If I should stay away from mouse click events, why or under what circumstances?"

(And, pre-emptive strike: I should stay away from Netbeans form designer.)

Was it helpful?

Solution

You should use the best tool for the job at hand. This means that for JMenuItems and for JButtons, you should use ActionListeners, not MouseListeners (exceptions notwithstanding). For instance if you disable a button, you want the button to not work, right? This works with ActionListeners but not with MouseListeners.

For the best information on this type of stuff, go to the source: Swing Tutorials.

OTHER TIPS

mnuEditDicAddAllScratch.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent actionEvent) {

         mnuEditDicAddAllScratchActionPerformed();
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top