DavidVV
DavidVV

Reputation: 235

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);
        setupVistaTablaMAterial(listener);
    }

    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();
        this.initListeners(listener);
    }


    private void initListeners (ActionListener listener) {
        getMostrarElementoButton().addActionListener(listener);
        getEliminarElementoButton().addActionListener(listener);

    }

     @Override
    public void actionPerformed(ActionEvent e) {

    }

}

Everything works fine if I delete the line:

getEliminarElementoButton().addAtionListener(listener);

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?

Upvotes: 0

Views: 40

Answers (1)

Bahramdun Adil
Bahramdun Adil

Reputation: 6079

The problem is in these lines:

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

That you are getting the same button for both.

Upvotes: 1

Related Questions