domingo, 3 de abril de 2011

JRadioButton, ButtonGroup, JCheckBox, JList, JComboBox (11.03.01)

El siguiente ejemplo muestra el uso de componentes de selección.
La creación de los componentes tiene los siguientes pasos.
- Declaracion de componentes
- Definir el subpanel
- Crear los componentes del subpanel
- Asignar el listener de eventos para el componente
- Agregar los componentes al subpanel
- Definir el listener de eventos.
- Opcionalmente se configura otras características de los componentes



ComponentesMain.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ComponentesMain {

    public static void main(String[] args) {
         SwingUtilities.invokeLater
         (  new Runnable() {
               public void run() { crearAplicacion(); }
            }
         );
    }

    private static void crearAplicacion() {
        //Asegurarse que contenga los decorators de una ventana.
        JFrame.setDefaultLookAndFeelDecorated(true);
        //se crea la ventana
        ComponentesContent ventanaPrincipal = new ComponentesContent();
    }

}

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

public class ComponentesContent {
    //La ventana y su panel
    private JFrame       frame;
    //Declaracion de componentes Radio Botton.
    private JRadioButton radio1, radio2, radio3, radio4;
    private ButtonGroup  grupo;
    //Declaracion de componentes Check Box
    private JCheckBox    check1, check2, check3, check4;
    //Declaracion de componentes Lista
    private JList jlist;
    //Declaracion de componentes Combo
    private JComboBox jcombobox;

    // Constructor de la ventana
    public ComponentesContent() {
        //Crear la ventana
        frame = new JFrame("Componentes");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
        //Crear el panel de la ventana
        LayoutManager layout = new FlowLayout();
        JPanel panel = new JPanel(layout);

        //Crear los subpaneles de la ventana
        JPanel subPanel1 = crearRadioButton();               
        JPanel subPanel2 = crearCheckBox();               
        JPanel subPanel3 = crearJList();               
        JPanel subPanel4 = crearJComboBox();    
       
        //agregarlos al panel principal          
        panel.add(subPanel1);
        panel.add(subPanel2);
        panel.add(subPanel3);
        panel.add(subPanel4);
       
        panel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

        //mostrar la ventana
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }

    //Crear un Radio Boton
    private JPanel crearRadioButton()
   {
        //definir el subpanel
        JPanel subPanel = new JPanel(new GridLayout(0, 1));
       
        //definir un grupo de botones
        grupo = new ButtonGroup();
       
        //crear los componentes del subpanel
        radio1 = new JRadioButton("AL-Alianza Lima");
        radio2 = new JRadioButton("U-Universitario");
        radio3 = new JRadioButton("SC-Sporting Cristal");
        radio4 = new JRadioButton("C-Cienciano");

        //agregar los radio boton al grupo
        grupo.add(radio1);
        grupo.add(radio2);
        grupo.add(radio3);
        grupo.add(radio4);

        //marcar el primer radio boton
        radio1.setSelected(true);
     
        //asignar el listener de eventos
        RadioBotonListener listener = new RadioBotonListener();
        radio1.addItemListener(listener);
        radio2.addItemListener(listener);
        radio3.addItemListener(listener);
        radio4.addItemListener(listener);

        //agregar los componentes al subpanel
        subPanel.add(radio1);
        subPanel.add(radio2);
        subPanel.add(radio3);
        subPanel.add(radio4);

        return subPanel;
    }  

    //Listener de eventos Radio Boton
    public class RadioBotonListener implements ItemListener {
        public void itemStateChanged(ItemEvent e) {
           
             JRadioButton radio = (JRadioButton)e.getItemSelectable();          
             if (radio.isSelected())
                  JOptionPane.showMessageDialog(frame, "Equipo: "+radio.getText());
        }
    }

    //Crear un Check Box
    private JPanel crearCheckBox()
   {
        //definir el subpanel
        JPanel subPanel = new JPanel(new GridLayout(0, 1));

        //crear los componentes del subpanel
        check1 = new JCheckBox("JC-JCreator");
        check2 = new JCheckBox("JB-JBuilder");
        check3 = new JCheckBox("EC-Eclipse");
        check4 = new JCheckBox("JD-JDeveloper");

        //marcar el primer check box
        check1.setSelected(true);

        //asignar el listener de eventos
        CheckBoxListener listener = new CheckBoxListener();
        check1.addItemListener(listener);
        check2.addItemListener(listener);
        check3.addItemListener(listener);
        check4.addItemListener(listener);

        //agregar los componentes al subpanel
        subPanel.add(check1);
        subPanel.add(check2);
        subPanel.add(check3);
        subPanel.add(check4);

        return subPanel;
    }

    //Listener de eventos Check Box
    public class CheckBoxListener implements ItemListener {
        public void itemStateChanged(ItemEvent e) {
           
             JCheckBox check = (JCheckBox)e.getItemSelectable();
             
             if (check.isSelected())
                  JOptionPane.showMessageDialog(frame, "Software : "+check.getText());
        }
    }

    //Crear una lista seleccionable
    private JPanel crearJList()
   {
        //definir el subpanel
        JPanel subPanel = new JPanel(new GridLayout(0, 1));
       
        //crear los componentes del subpanel
        String[] items = {"FU-Futbol",
                          "VO-Voleibol",
                          "TE-Tenis",
                          "BE-Beisbol",
                          "BO-Boxeo",
                          "SU-Surf",
                          "NA-Natacion"};

        //crear la lista
        jlist = new JList(items);
       
        //indicar cuantos elementos seran visibles
        jlist.setVisibleRowCount(5);
        //configurar para seleccionar un elemento
        jlist.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //opcionalmente agregar un Tool Tip
        jlist.setToolTipText("Es un JList");
       
        //enmarcar la lista en un scroll
        JScrollPane jscrollpane = new JScrollPane(jlist);
       
        //asignar el listener de eventos
        JListListener listener = new JListListener();
        jlist.addListSelectionListener(listener);

        //agregar los componentes al subpanel
        subPanel.add(jscrollpane);
       
        return subPanel;
    }

    //Listener de eventos de la Lista
    public class JListListener implements ListSelectionListener {
        public void valueChanged(ListSelectionEvent e)
        {
            String mensaje = "Juego : "+(String)jlist.getSelectedValue();
            JOptionPane.showMessageDialog(frame, mensaje);           
        }
    }

    //Crear una combo seleccionable
    private JPanel crearJComboBox()
   {
        //definir el subpanel
        JPanel subPanel = new JPanel(new GridLayout(0, 1));
       
        //crear los componentes del subpanel
        jcombobox = new JComboBox();

        jcombobox.addItem("L39-Los Olivos");
        jcombobox.addItem("L28-Independencia");
        jcombobox.addItem("L31-San Martin");
        jcombobox.addItem("L25-Rimac");
        jcombobox.addItem("L07-Comas");

        //seleccionar un elemento por defecto
        jcombobox.setSelectedItem("L25-Rimac");

        //asignar el listener de eventos
        JComboBoxListener listener = new JComboBoxListener();
        jcombobox.addActionListener(listener);

        //agregar los componentes al subpanel
        subPanel.add(jcombobox);
       
        return subPanel;
    }

    //Listener de eventos del Combo
    public class JComboBoxListener implements ActionListener {
        public void actionPerformed(ActionEvent e)
        {
            String mensaje = "Distrito : "+(String)jcombobox.getSelectedItem();
            JOptionPane.showMessageDialog(frame, mensaje);
        }
    }

}

Compartir:

0 comentarios:

Publicar un comentario