lunes, 11 de junio de 2012

ItemListener

Siguiente con el ejemplo anterior donde explicamos el uso de la interfaz ActionListener, hoy le toca el turno a ItemListener, esta interfaz es usada generamente en los controles como CheckBox o RadioButton, de manera de detectar el evento en el momento en que se produce.
Les dejo un breve ejemplo para que lo puedan experimentar:


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

public class EjemploJCheckBox extends JFrame {
  
  
  private JButton boton;
  private JCheckBox ckControl;
  
  public EjemploJCheckBox() {
    
    setTitle("Ejemplo");
    
    JPanel panel = new JPanel(new FlowLayout());
    
    
    JPanel controles = new JPanel(new GridLayout(1,2));
    
    ckControl = new JCheckBox("Habilitar");
    ckControl.setSelected(true);
    
    CheckListener checkListener = new CheckListener();
    ckControl.addItemListener(checkListener);
    
    
    boton = new JButton("Boton");
    
    ButtonListener buttonListener = new ButtonListener();
    boton.addActionListener(buttonListener);
    
    controles.add(ckControl);
    controles.add(boton);
    
    panel.add(controles);
    
    setContentPane(panel);
    
    setVisible(true);
    pack();
  }
  
  
  public static void main(String[] args) {
    EjemploJCheckBox frame = new EjemploJCheckBox();
  }
  
  
  public class CheckListener implements ItemListener {
    
      public void itemStateChanged(ItemEvent e) {
      
        
        boton.setEnabled(ckControl.isSelected());
        
      }
      
   }
   
   
  public class ButtonListener implements ActionListener {
    
    
      public void actionPerformed(ActionEvent e) {
        
        dispose();
        
      }
      
   }
   
}

No hay comentarios:

Publicar un comentario