Carregar um combo box a partir de outro combo box

2 respostas
V

Boa tarde,

Gostaria por favor da ajude de vcs!
Queria saber como faço para carregar uma lista num combo box apartir de outro combo box.
No caso estarei selecionando 1 informação de um combo box, e através dessa informação carregarei outra combo.
No meu exemplo que estou fazendo as combos são de Estado(UF) e cidade.

Agradeço desde já,

Vitor Bonfim

2 Respostas

Mantu

A classe JComboBox tem um método chamado addItemListener, no qual você registra um objeto (de uma classe que implemente a interface ItemListener) responsável por responder ao evento de troca de item selecionado no combo. Você pode fazer a carga do outro combo na implementação do método itemStateChanged da objeto registrado.
Dê uma lisa neste tópico que aborda sobre tratamento de eventos:
http://www.guj.com.br/posts/list/65196.java#343609

EDIT

Mátodo é dose… :shock:

Ironlynx
Leia com *muito carinho* o link que o Mantu postou.Mas esse exemplo também pode lhe ajudar:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;

public class ComboBoxTwo extends JFrame implements ActionListener{
	private JComboBox mainComboBox;
	private JComboBox subComboBox;
	private Hashtable subItems = new Hashtable();
 
	public ComboBoxTwo(){
		String[] items = { "Select Item", "Color", "Shape", "Fruit" };
		mainComboBox = new JComboBox( items );
		mainComboBox.addActionListener( this );
 
		//  In JDK1.4 this prevents action events from being fired when the
		//  up/down arrow keys are used on the dropdown menu
 
		mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
		getContentPane().add( mainComboBox, BorderLayout.WEST );
 
		//  Create sub combo box with multiple models 
		subComboBox = new JComboBox();
		subComboBox.setPrototypeDisplayValue("XXXXXXXXXXXX"); // JDK1.4
		getContentPane().add( subComboBox, BorderLayout.EAST );
 
		String[] subItems1 = { "Select Color", "Red", "Blue", "Green" };
		subItems.put(items[1], subItems1);
 
		String[] subItems2 = { "Select Shape", "Circle", "Square", "Triangle" };
		subItems.put(items[2], subItems2);
 
		String[] subItems3 = { "Select Fruit", "Apple", "Orange", "Banana" };
		subItems.put(items[3], subItems3);
	}
 
	public void actionPerformed(ActionEvent e){
		String item = (String)mainComboBox.getSelectedItem();
		Object o = subItems.get( item );
 
		if (o == null){
			subComboBox.setModel( new DefaultComboBoxModel() );
		}
		else{
			subComboBox.setModel( new DefaultComboBoxModel( (String[])o ) );
		}
 
		//  make sure popup is closed when 'isTableCellEditor' is used 
		mainComboBox.hidePopup();
	}
 
	public static void main(String[] args){
		  JFrame frame = new ComboBoxTwo();
		   frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
		   frame.pack();
		   frame.setLocationRelativeTo( null );
	       frame.setVisible( true );		
	 }
}
Criado 5 de março de 2008
Ultima resposta 5 de mar. de 2008
Respostas 2
Participantes 3