1

I'm training with GUI in Java. I use JMenuBar

JMenuBar menuBar = new JMenuBar();

in this there is JMenu

JMenu fileMenu = new JMenu("File");

in the bar there are two JMenuItem

JMenuItem creditsItem = new JMenuItem("Credits");
JMenuItem preferenceItem = new JMenuItem("Option");

So I add everything to the bar and to the menu:

menuBar.add(fileMenu);
fileMenu.add(creditsItem);
fileMenu.add(preferenceItem);

Then I want perform different actions depending which of the two ItemMenu in clicked, in particular I want open two differents JDialog

creditsItem.addMouseListener(this);
preferenceItem.addMouseListener(this);

After implementing MouseListener

class MainFrame extends JFrame implements MouseListener

I have to use

@Override
    public void mouseReleased(MouseEvent e) {
        System.out.println("Clicked!!");
    }

But the problem is recognizing which of the two JMenuItem has been clicked. I've tought of using switch, but how to know which of the two is clicked is the problem.

Mitro
  • 1,230
  • 8
  • 32
  • 61
  • 1
    you can use this [Mouselistener][1] http://java-program-sample.blogspot.in/2011/09/implementing-event-listener-on.html [1]: http://stackoverflow.com/questions/8589605/menulistener-implementation-how-to-detect-which-jmenu-was-clicked – Shriram Mar 20 '14 at 12:44
  • Oh cool, I didn't know about MenuListener and so I didn't found this question, Thank you! – Mitro Mar 20 '14 at 12:47
  • @Shriam addMenuListener works only for JMenu and not for JMenuItem – Mitro Mar 21 '14 at 10:04

1 Answers1

1

The best thing to do is

@Override
    public void mouseReleased(MouseEvent e) {

        if(e.getSource()==preferenceItem){
        System.out.println("PreferenceItem");
        optionDialog = new OptionDialog();
        }
        if(e.getSource()==printItem){
        System.out.println("PrintItem");
        }

    }

after implementing MouseListener instead of MenuListener

Skizzato
  • 26
  • 4