Boa Dia a tods, estou com um problemão aqui, eu possuo dois combobox e preciso q um seja atualizado de acordo com a opção escolhida no outro em tempo de execução, caso semelhante a um sistema em que o usuário escolhe o estado em um combobox e em outro ja são carregados as cidades referentes a esse estado.
//COMBOBOX ORIGEM
private JComboBox getJComboBoxModelo() {
if (jComboBoxModelo == null) {
jComboBoxModelo = new JComboBox();
jComboBoxModelo.setBounds(143, 7, 128, 20);
jComboBoxModelo.setModel(new DefaultComboBoxModel(PrintThreadMapaTrabalho.MODELO));
ComponentUIProps.getInstance().setComboBox(jComboBoxModelo);
jComboBoxModelo.setSelectedIndex(0);
jComboBoxModelo.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent e) {
enableComponents();
}
});
}
return jComboBoxModelo;
}
//COMBOBOX DESTINO, QUE DEVE SER ATUALIZADO
private JComboBox getJComboBoxAgruparPor() {
if (jComboBoxAgruparPor == null) {
jComboBoxAgruparPor = new JComboBox();
jComboBoxAgruparPor.setBounds(143, 28, 128, 20);
jComboBoxAgruparPor.setModel(new DefaultComboBoxModel(SQLQueryMapaTrabalho.AGRUPAR_POR));
ComponentUIProps.getInstance().setComboBox(jComboBoxAgruparPor);
jComboBoxAgruparPor.setSelectedIndex(1);
}
return jComboBoxAgruparPor;
}
private void enableComponents() {
if (sel == PrintThreadMapaTrabalho.MODELO_RESUMO) {
jComboBoxAgruparPor.setEnabled(true);
}else if (sel == PrintThreadMapaTrabalho.MODELO_INDIVIDUAL){
jComboBoxAgruparPor.setModel(new DefaultComboBoxModel(SQLQueryMapaTrabalho.AGRUPAR_POR_PAC));
}
sendo que por padrão o combobox deve carregar a lista AGRUPAR_POR e quando selecionado o MODELO_INDIVIDUAL ele deve atualizar o combox destino coma lista AGRUPAR_POR_PAC e vice e versa.
fico no aguardo…até mais
Porco no seu JComboBox de origem você coloca no ActionListener o que é pra ser realizado sobre o JComboBox de destino, como o exemplo abaixo:
combo1 = new JComboBox();
combo1.addItem("Mostrar Letras");
combo1.addItem("Mostrar Números");
combo1.setBounds(10, 10, 200, 20);
this.getContentPane().add(combo1);
combo1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
combo2.removeAllItems();
if(combo1.getSelectedItem().toString().equals("Mostrar Letras")){
combo2.addItem("A");
combo2.addItem("B");
combo2.addItem("C");
}
else{
combo2.addItem("1");
combo2.addItem("2");
combo2.addItem("3");
}
}
});
combo2 = new JComboBox();
combo2.setBounds(10, 35, 200, 20);
this.getContentPane().add(combo2);
Desculpa a desorganização, qualquer coisa estamos ai!
só que noi meu caso eu teria que puxar uma lista referente a escolha feita…
tipo o combobox ja existe na tela…por exemplo o tem o combo1 que abre como padrao o item1 assim sendo o combo2 também tera o item1, só que qndo eu alterar para item2 no comb1 o combo 2 tera de ser alterado para o item2 também
Com o codigo que o ThgVieira colocou acima você consegue fazer oq ta precisando…
no evento ActionListener você consegue pegar o valor que foi selecionado no Combo
Object vlCombo = combo1.getSelectedItem();
e depois é so adicionar o vlCombo no combo2
combo2.addItem(vlCombo);
Agora, para deixar o item selecionado no combo2 você precisa percorrer os itens do combo2 e encontrar o indice do valor. Encontrando o index do valor que voce quer deixar selecionado no combo2, é so dar um selectIndex(index) no combo2.
Tenta ai… qq coisa posta de novo…
pior q não funciona… eu adicionei uma lista no combo2 através do Listener do combo1, até debuguei o código e no model ele parecem os itens que devem ser adicionado no combo2 mais eles não são inseridos, tentei dar um repaint() também no combo2 e nda, o combo2 continua com os mesmos itens que estavam antes.
consegui atualiza-los…porém agora esta ocorrendo um erro quando a tela é chamada o erro é o seguinte…
java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
at java.awt.Component.getLocationOnScreen_NoTreeLock(Unknown Source)
at java.awt.Component.getLocationOnScreen(Unknown Source)
at javax.swing.JPopupMenu.show(Unknown Source)
at javax.swing.plaf.basic.BasicComboPopup.show(Unknown Source)
at javax.swing.plaf.basic.BasicComboBoxUI.setPopupVisible(Unknown Source)
at javax.swing.JComboBox.setPopupVisible(Unknown Source)
at br.com.is.commons.ui.combobox.AutoCompletion.insertString(Unknown Source)
at javax.swing.text.AbstractDocument.replace(Unknown Source)
at javax.swing.text.JTextComponent.setText(Unknown Source)
at javax.swing.plaf.metal.MetalComboBoxEditor$1.setText(Unknown Source)
at javax.swing.plaf.basic.BasicComboBoxEditor.setItem(Unknown Source)
at javax.swing.JComboBox.configureEditor(Unknown Source)
at javax.swing.plaf.basic.BasicComboBoxUI$Handler.propertyChange(Unknown Source)
at javax.swing.plaf.basic.BasicComboBoxUI$PropertyChangeHandler.propertyChange(Unknown Source)
at de.muntjak.tinylookandfeel.TinyComboBoxUI$TinyPropertyChangeListener.propertyChange(TinyComboBoxUI.java:95)
at java.beans.PropertyChangeSupport.firePropertyChange(Unknown Source)
at java.beans.PropertyChangeSupport.firePropertyChange(Unknown Source)
at java.awt.Component.firePropertyChange(Unknown Source)
at javax.swing.JComboBox.setModel(Unknown Source)
at br.com.is.isenterprise.lab.ui.report.JPanelReportMapaTrabalho.attribLastUsedParameter(JPanelReportMapaTrabalho.java:1064)
at br.com.is.isenterprise.lab.ui.report.JPanelReportMapaTrabalho.initializeReport(JPanelReportMapaTrabalho.java:362)
at br.com.is.isenterprise.shared.ui.report.JFrameReport.afterInitialize(JFrameReport.java:122)
at br.com.is.isenterprise.shared.ui.report.JFrameReport.<init>(JFrameReport.java:66)
at br.com.is.isenterprise.ISEnterprise.openReport(ISEnterprise.java:655)
at br.com.is.isenterprise.ISEnterprise.openCommandItem(ISEnterprise.java:597)
at br.com.is.isenterprise.ISEnterprise.treeAction(ISEnterprise.java:697)
at br.com.is.isenterprise.shared.ui.MenuCreator$1.mouseReleased(MenuCreator.java:272)
at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
este erro ocorre quando eu tento setar o novo model ao combobox
jComboBoxAgruparPor.setModel(new DefaultComboBoxModel(SQLQueryMapaTrabalho.AGRUPAR_POR_INDIVIDUAL));
e só acontece quando tento inicializar a tela com esse model, se a telafor inicializada com outro model e no decorrer da execução eu quiser trocar ela aceita de boua…