16

I was wondering if can you test to see if a JMenu (not JMenuItem) has been clicked. I tried adding an ActionListener to it but it doesn't seem to recognize it. I just need it to preform an action when the JMenu button is pressed so that I can change the JMenuItems for that menu befor it opens. All work arrounds to get this result are welcome too!

Thanks

mre
  • 43,520
  • 33
  • 120
  • 170
clankfan1
  • 225
  • 2
  • 3
  • 10

3 Answers3

21
  • for JMenu use MenuListener

code

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class ActionExample {

    public ActionExample() {

        JMenu menu = new JMenu("Menu");
        menu.setMnemonic(KeyEvent.VK_M);
        menu.addMenuListener(new SampleMenuListener());
        JMenu menu1 = new JMenu("Tool");
        menu1.setMnemonic(KeyEvent.VK_T);
        menu1.addMenuListener(new SampleMenuListener());
        JFrame f = new JFrame("ActionExample");
        JMenuBar mb = new JMenuBar();
        mb.add(menu);
        mb.add(menu1);
        f.setJMenuBar(mb);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                ActionExample actionExample = new ActionExample();
            }
        });
    }
}

class SampleMenuListener implements MenuListener {

    @Override
    public void menuSelected(MenuEvent e) {
        System.out.println("menuSelected");
    }

    @Override
    public void menuDeselected(MenuEvent e) {
        System.out.println("menuDeselected");
    }

    @Override
    public void menuCanceled(MenuEvent e) {
        System.out.println("menuCanceled");
    }
}
Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
0

I think it's possible to use a MouseListener to fire actions in JMenu without JMenuItem.

JMenu myMenu = new JMenu("My menu");

myMenu.addMouseListener(new MouseListener() {
  @Override
  public void mouseClicked(MouseEvent e) {
    // action here
  }

  @Override
  public void mousePressed(MouseEvent e) {
  }

  @Override
  public void mouseReleased(MouseEvent e) {
  }

  @Override
  public void mouseEntered(MouseEvent e) {
  }

  @Override
  public void mouseExited(MouseEvent e) {
  }
});

menuBar.add(myMenu);
Michael
  • 71
  • 1
  • 5
-1

With an instance of JMenu you can't add an ActionListener, only with JMenuItem you can do it.

Antonio1996
  • 736
  • 2
  • 7
  • 22
  • We can add an `ActionListener` to `JMenu`, but it just doesn't have any effect. JMenu opens its child `JMenu`s and `JMenuItem`s when the mouse hovers over it. I think the question is about the extra functionality to perform an action when clicking on the `JMenu`. – Hummeling Engineering BV Jun 02 '22 at 06:18