Question

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?

Was it helpful?

Solution

Sounds like the developers of Java languare forget to propagate events from menuItems using addActionListener.

No, the developers suggest that you use Action "to separate functionality and state from a component."

OTHER TIPS

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:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top