How do I get the name of a button in Mouselistener?

Asked

Viewed 674 times

1

How do I get the name of a button in a class that implements Mouselistener:

public class Viewer extends javax.swing.JFrame{
    public Viewer() {
        initComponents();
    }

    public void init(){
        MouseListener ouvinte = new MouseListener();
        btn00.addMouseListener(ouvinte);
    }
}

public class MouseListener implements java.awt.event.MouseListener{

@Override
    public void mouseClicked(MouseEvent me) {
        Model modelo = new Model();
        //Como consigo obter o nome do botão "btn00" nesta classe?

        if(modelo.validarJogada(getName(), 1))

        }
    }
}

1 answer

3


You must call the method getSource() in your Mouseevent object, it will return exactly the object that called the method.

It is a good idea before assigning this object to a variable to make a check if it was really a Jbutton that called it, because the mouseClicked() can be called by numerous different types of components, if it was a Jbutton your code will be safe to cast. Example:

@Override
public void mouseClicked(MouseEvent me) {
    if(me.getSource() instanceof JButton) {    //confere se objeto é do tipo JButton
        JButton b = (JButton) me.getSource();  //faz um cast e atribui a uma variavel
        System.out.println(b.getName());       //chama um método do JButton
    }
}
  • This b will store the button object calling the method?

  • @Turibamalabeech!

Browser other questions tagged

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