Domanda

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.

È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top