DavidVV DavidVV - 11 months ago 73
Java Question

JAVA After adding a seccond button and its actionListener, actions get executed twice

After adding a listener to a second button, the first created button executes twice the same action:

public class ControladorTablaMaterial implements ActionListener {

private VistaTablaMaterial vistaTablaMaterial;
private JPanel jContentPane = null;
private JScrollPane scrollPane = null;
private JTable tablaMaterial;
private JButton mostrarElementoButton;
private JButton eliminarElementoButton;
private ModeloTablaMaterial modeloTablaMaterial;

public ControladorTablaMaterial(ArrayList<Material> coleccionMaterial, ActionListener listener) {
String[] cabecera = {"Material", "Titulo"};
this.vistaTablaMaterial = new VistaTablaMaterial(cabecera, coleccionMaterial);

private void setupVistaTablaMAterial(ActionListener listener) {
this.scrollPane = vistaTablaMaterial.getScrollPane();
this.tablaMaterial = vistaTablaMaterial.getTablaMaterial();
this.modeloTablaMaterial = vistaTablaMaterial.getModeloTablaMaterial();
this.mostrarElementoButton = vistaTablaMaterial.getMostrarElementoButton();
this.eliminarElementoButton = vistaTablaMaterial.getMostrarElementoButton();

private void initListeners (ActionListener listener) {


public void actionPerformed(ActionEvent e) {



Everything works fine if I delete the line:


but of course I need that button to be listened to too.

Inside the listener class, in the actionPerformed(actionEvent e) method, I use the following code to differentiate both buttons:

if (e.getSource().equals(this.getControladorTablaMaterial().getMostrarElementoButton())) {

That seems to work fine except for this frame. Any guess?

Off topic: why isn't the code indentation working properly on Stackoverflow's editor?


The problem is in these lines:

this.mostrarElementoButton = vistaTablaMaterial.getMostrarElementoButton();
this.eliminarElementoButton = vistaTablaMaterial.getMostrarElementoButton();

That you are getting the same button for both.