Doubt in the implementation of ActionListener

1

I have a college project to make a system of any category which in the case I chose a medical system and had something I did not quite understand about what the implementation would be like:

I have a JInternalFrame called CadastroMedico with several text fields for the information and buttons like Save Registration, Delete Registration etc ...

I was asked to create a class called MedicoListener where all actions of class CadastroMedicos would be implemented in a single ActionListener , where it would see which button was pressed and perform such action, and that's where I I did not get the thread (I have a Medical class with getters & setters).

How would the correct implementation of this be?

The MedicalListener class follows:

public class MedicoListener implements ActionListener {

Medico med = new Medico();
private CadastroMedico frame;

public MedicoListener(CadastroMedico frame){
    this.frame = frame;

}

@Override
public void actionPerformed(ActionEvent e) {

    //SALVAR


    //EXCLUIR

}
    
asked by anonymous 10.09.2016 / 15:52

2 answers

1

You can define " Actions commands " for the buttons and then filter inside the Listener via a switch :

@Override
public void actionPerformed(ActionEvent e) {
   String ActCmd = e.getActionCommand();

   switch(actCmd){

  case "SALVAR":
     //aqui você faz a lógica do salvar
     break;
  case "EXCLUIR":
     //logica do excluir

   }

}

And in the buttons, you need to make a small change by adding actions command similarly below:

JButtonSalvar.setActionCommand("SALVAR");
JButtonExcluir.setActionCommand("EXCLUIR");

The above change needs to be made in the build class of the screen, if you are using the netbeans GUI builder, just add after the initComponents() method in the class constructor.

As a suggestion, create separate methods to do such actions (separate method to save and delete), if they are complex, and just call the specific method inside the switch ... case for the code to be more organized. >     

10.09.2016 / 16:15
0

To know which button triggered the event, you can use getSource of ActionEvent :

String comando = ((JButton) e.getSource()).getText();
if (isComandoSalvar())
   //Chamar comando salvar
else
   //Chamar comando remover

In this way, based on the button label that triggered the event, it will be possible to identify the operation to be called, whether it will save or delete the record. You could retrieve this information from another JButton attribute, the important thing here is to understand that the component information that triggers the event is encapsulated in ActionEvent and is accessible by the getSource method.

    
10.09.2016 / 16:18