The mouseclicked event for menu item does not work for me

0

The event mouseclicked for menu item in swing does not work for me. I changed it to mousepressed and it works for me ... it's practically the same, but I wanted to know why this does not work in a menu item.

EDITED: the code was generated automatically by graphical interface. I decided to simply go for using ActionPerformed for all the events ..

    
asked by Alejandro Mayorga 19.02.2017 в 04:13
source

1 answer

1

The JMenuItem is subclass of AbstractButton . Generally it works well to simply implement ActionListener in your JFrame and react to your menu in actionPerformed(ActionEvent e) .

public class MiClase extends JFrame implements ActionListener{
    ...
    // necesitas un campo en tu clase para la referencia desde actionPerformed
    JMenuItem m1; 

    // en el constructor
    public Miclase(){
        m1 = new JMenuItem("menu 1");
        m1.addActionListener(this);
    ...
    }
    ...
    public void actionPerformed(ActionEvent e){
        if (e.getSource() == m1) hazAlgo();
        ...
    }

To better control the context of the action, you can use getModifiers() and / or getId() of the ActionEvent (API in English) .

    
answered by 19.02.2017 в 05:08