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

1

How do I get the name of a button in a class that implements the 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))

        }
    }
}
    
asked by anonymous 19.05.2014 / 01:11

1 answer

3

You should call the getSource() method on 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 even a JButton that called it because the mouseClicked() can be called by several different types of components, if it was a JButton its code will be safe to make a 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
    }
}
    
19.05.2014 / 01:46