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?
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: