How to make different actions when pressing a button?

0

I have found myself in a problem when doing a Java program, and that is that as I have the code it does not matter what button I press that is always going to execute the command of button 1 I think it is because I am wrongly selecting what what happens in the if structure but I'm not sure. The code that I leave is the one of the class that is in charge of that section since I have to do it in different windows and the previous one that a Login works well for me.

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class MarcoEleccion extends JFrame{

public MarcoEleccion(){

    setTitle("Eleccion");
    setBounds(500,500,400,400);

    LaminaEleccion milamina=new LaminaEleccion();
    add(milamina);

    setVisible(true);
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

}

}

class LaminaEleccion extends JPanel{

public LaminaEleccion(){

    texto1=new JLabel("Selecciona una opcion");
    add(texto1);

    boton1 = new JButton("Entrada");
    boton2 = new JButton("Salida");
    boton3 = new JButton("Cerrar");
    add(boton1);
    add(boton2);
    add(boton3);
    boton1.addActionListener(evento1);
    boton2.addActionListener(evento1);
    boton3.addActionListener(evento1);

}

class EventoEleccion implements ActionListener{

    public void actionPerformed(ActionEvent e) {

        if (boton1.isEnabled()){

            System.out.println("Entrada");

        }else if (boton2.isEnabled()){

            System.out.println("Salida");

        }else if (boton3.isEnabled()){



        }

    }

}

private JButton boton1;
private JButton boton2;
private JButton boton3;
private JLabel texto1;
private EventoEleccion evento1=new EventoEleccion();

}

Thanks in advance for the help.

    
asked by Acoidan Negrín Socorro 09.01.2018 в 15:18
source

1 answer

2

You need to identify in the ActionEvent, which button triggered the event:

  public void actionPerformed(ActionEvent e) {

       JButton source = (JButton)e.getSource(); //Tomas la fuente del evento

            if (boton1 == source  ){
                 //Si la fuente es igual al botón 1 -> Acción 
                System.out.println("Entrada");      
            }else if (boton2 == source ){
                //Si la fuente es igual al botón 1 -> Acción
                System.out.println("Salida");     
            }else if (boton3 == source ){
                //Si la fuente es igual al botón 1 -> Acción
            }

        }
    
answered by 09.01.2018 / 15:49
source