How to add Mouseclicked to a Jlabel?

Asked

Viewed 463 times

1

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

For example, for the buttons I do so:

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
        }
    }
  • swing? If it is he already works with this concept. I think it’s silly to go around creating something that java already does to make our life easier.

  • But in MVC it would not be done differently?

1 answer

2


If the intention is just to perform some action when the mouse is clicked, simply override the method mouseClicked 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 a part, as demonstrated in the code, just do so:

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

And create another extending class MouseAdapter(can be implementing MouseListener also, but will require to implement all mouse event methods):

class MouseEventos extends MouseAdapter{

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.