
package interfazgrafica9;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class GestorEventos extends WindowAdapter implements ActionListener, ListSelectionListener {
    
      private Componentes componentes;
    
    public GestorEventos(Componentes componentes) {
        this.componentes = componentes;
    }

         // MÉTODOS DE WindowAdapter     
   public void windowClosing(WindowEvent e) {
      System.exit(0);
   }     
   
         // MÉTODO DE ActionListener   
    public void actionPerformed(ActionEvent e) { 
        
          switch(e.getActionCommand())
          {                                    
             case "botonAñadir" :   
                     if (componentes.getjTextfield().getText().compareTo("")!=0)
                        { componentes.getDefaultListModel().addElement(componentes.getjTextfield().getText());
                          componentes.getjList().setSelectedIndex(0);
                          componentes.getjTextfield().setText("");                         
                        }
                     break;    
             case "botonVaciar" :   
                     if (componentes.getDefaultListModel().getSize()>0)
                     { componentes.getDefaultListModel().removeAllElements();
                       componentes.getjTextfield().setText("");
                     }
                     break;
             case "botonEliminar" :   
                      if (componentes.getDefaultListModel().getSize()>0)
                      {  componentes.getDefaultListModel().remove(componentes.getjList().getSelectedIndex());
                         if (componentes.getDefaultListModel().getSize()>0)
                         {  componentes.getjList().setSelectedIndex(0); }
                      }
                     break;                     
          }
    } 
    
         // MÉTODO DE ListSelectionListener     
    public void valueChanged(ListSelectionEvent e) { 
        JList jList = (JList) e.getSource();
     
        if (jList == componentes.getjList())
           if (!componentes.getjList().isSelectionEmpty())
              componentes.getjTextfield().setText(componentes.getjList().getSelectedValue().toString());
    }    
}
