How to add MouseClicked to a JLabel?

1

I'm creating a program with MVC rules in Java and would like to know how to create an Event in a JLabel when I click on it with the mouse.

For example, for buttons I do this:

View class:

void addLogarListener(ActionListener cal) {
        btnLogar.addActionListener(cal);
    }

Controller class:

view.addLogarListener(new LogarListener());
//===================================
class LogarListener implements ActionListener {
        public void actionPerformed(ActionEvent evento) {
             //Comandos
        }
    }
    
asked by anonymous 21.11.2016 / 14:23

1 answer

2

If the intention is just to perform some action when the mouse is clicked, just overwrite the mouseClicked method as below:

seuLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent arg0) {
            //aqui as operações quando o label for clicado
            }
        });

Or if you prefer to do with a class as shown in the code, just do the following:

//no seu label, você adicionar um mouselistener e passa uma instancia
//nova da classe personalizada
seuLabel.addMouseListener(new MouseEventos());

And create another class by extending MouseAdapter

21.11.2016 / 14:33