Para realizar esta funcionalidad estaremos trabajando con las clases:
- ComboBoxModel.
- ListDataEvent.
- ListDataListener.
Bueno para empezar crearemos una clase de nombre Datos, esta clase tendrá 3 atributos que son :
- codigo
- nombre
- edad
public class Datos<list> {
private int codigo;
private String nombre;
private int edad;
/**
* @return the codigo
*/
public int getCodigo() {
return codigo;
}
/**
* @param codigo the codigo to set
*/
public void setCodigo(int codigo) {
this.codigo = codigo;
}
/**
* @return the nombre
*/
public String getNombre() {
return nombre;
}
/**
* @param nombre the nombre to set
*/
public void setNombre(String nombre) {
this.nombre = nombre;
}
/**
* @return the edad
*/
public int getEdad() {
return edad;
}
/**
* @param edad the edad to set
*/
public void setEdad(int edad) {
this.edad = edad;
}
@Override
public String toString() {
return nombre ;
}
public Datos(int codigo, String nombre, int edad) {
this.codigo = codigo;
this.nombre = nombre;
this.edad = edad;
}
public Datos() {
}
}
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import javax.swing.ComboBoxModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
public class ProveedorDatos implements ComboBoxModel {
private List<datos> listaDatos = new ArrayList<datos>();
private List<listdatalistener> listaListener = new ArrayList<listdatalistener>();
private Datos datos;
public ProveedorDatos() {
cargarDatos();
}
private void cargarDatos() {
for (int i = 1; i <= 10; i++) {
datos = new Datos(i, "Nombre " + i, i);
listaDatos.add(datos);
}
}
public List tomarDatos() {
return listaDatos;
}
public void setSelectedItem(Object selectedIn) {
if (selectedIn instanceof Datos) {
datos = (Datos) selectedIn;
} else {
datos = null;
}
ListIterator<listdatalistener> ldL = listaListener.listIterator();
while (ldL.hasNext()) {
ListDataListener ldl = (ListDataListener) ldL.next();
ldl.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, 0));
}
}
public Object getSelectedItem() {
return datos;
}
public int getSize() {
return listaDatos.size();
}
public Object getElementAt(int index) {
return listaDatos.get(index);
}
public void addListDataListener(ListDataListener ldl) {
listaListener.add(ldl);
}
public void removeListDataListener(ListDataListener ldl) {
listaListener.remove(ldl);
}
public String getSelectedDescriscripcion() {
if (datos == null) {
return null;
} else {
return datos.getNombre();
}
}
public int getSelectedCodigo() {
if (datos == null) {
return -1;
} else {
return datos.getCodigo();
}
}
}
Por último usaremos la clase ventana
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Ventana extends JFrame implements ActionListener {
private JComboBox combo1;
private JButton boton1;
private String strTitulo;
public Ventana(String tituloIn) {
strTitulo = tituloIn;
}
public Ventana() {
}
public void iniciarComponentes() {
ResolucionPantalla res;
Container contenedor1;
combo1 = new JComboBox(new ProveedorDatos());
boton1 = new JButton("Aceptar");
boton1.setActionCommand("aceptar");
boton1.addActionListener(this);
contenedor1 = getContentPane();
contenedor1.setLayout(new FlowLayout());
contenedor1.add(combo1);
contenedor1.add(boton1);
setVisible(true);
setTitle(strTitulo);
//le damos un tamaño a la pantalla
setSize(300, 100);
//centrar pantalla
res = new ResolucionPantalla();
setLocation(res.centrarPantalla(this));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent evento) {
if (evento.getActionCommand().equals("aceptar")) {
ProveedorDatos datosCombo;
StringBuilder builder;
datosCombo = (ProveedorDatos) combo1.getModel();
builder = new StringBuilder();
builder.append("Código :").append(datosCombo.getSelectedCodigo()).
append("\n");
builder.append("Descripción: ").append(datosCombo.getSelectedDescriscripcion());
JOptionPane.showMessageDialog(null, builder.toString(),
"Datos Seleccionados", JOptionPane.INFORMATION_MESSAGE);
}
}
public static void main(String arg[]) {
Ventana iniciar;
iniciar = new Ventana("Obtener código y descripción");
iniciar.iniciarComponentes();
}
}
Este es el resultado:
3 comentarios:
Excelente Aporte; Se le agradece y se le motiva a que continué compartiendo sus conocimientos y experiencia. Muchas gracias
Muy buen aporte!
Todo funciona perfecto, solo que la lista que se despliega en el comboBox muestra Util.Norma@17d0e70, estos son los objetos que eh cargado, pero me gustaria que solo se vizualice la descripcion.
Como lo puedo solucionar?
Hola, recuerda sobre-escribir el método toString()
@Override
public String toString() {
return nombre ;
}
Publicar un comentario