How to detect mouse click on menuItem when added via addMouseListener

Vadim picture Vadim · Sep 24, 2011 · Viewed 9k times · Source

Consider you want to close your java application using "Close application" menu item.

3 possible solutions are (using ActionListener or MouseAdapter or MouseListener):

menuItemClose.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub
        System.exit(0);
    }
});

menuItemClose.addMouseListener(new MouseAdapter() {

    @Override
    public void mouseClicked(MouseEvent e) {
        System.exit(0);
    }
});

menuItemClose.addMouseListener(new MouseListener() {

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub
        System.exit(0);
    }
});

3 solutions, and only first one fires.

What is the explanation of this? Does some other componenets have same behavior? How to properly handle events in such cases?

Answer

mre picture mre · Sep 24, 2011

In that example, you never register a KeyListener. Anyway, you should only register an ActionListener. For more information, see Handling Events from Menu Items.

See also: