在swing中绑定combobox

我正在使用Eclipse IDE开发桌面(swing)应用程序。 我有三个combobox(国家,州和城市),我需要在选择新的国家或省时自动更新数据。 我搜索了很多信息,但我发现的所有实现都是在Ajax或NetBeans中的豆类绑定框架上完成的。 我尝试了ItemEvent的解决方案,但我在启动应用程序时遇到问题,它加载了国家/地区列表而不是其他列表。 通过选择一个国家/地区,将收取州名单,但不包括城市列表。

我的代码:

jComboBoxCountries.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { jComboBoxStates.setModel(new javax.swing.DefaultComboBoxModel( statesOf(evt.getItem()).toArray() )); } }); jComboBoxStates.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { jComboBoxCities.setModel(new javax.swing.DefaultComboBoxModel( citiesOf(evt.getItem()).toArray()) ); } }); jComboBoxCountries.setModel(new javax.swing.DefaultComboBoxModel( countryList.toArray())); 

我在启动应用程序时遇到问题,它会加载国家/地区列表但不会加载其他列表

您似乎必须专门设置所选索引才能调用侦听器。

 jComboBoxCountries.setModel(...) jComboBoxCountries.setSelectedIndex(0); 

通过选择一个国家/地区,将收取州名单,但不包括城市列表。

我猜这是同样的问题,一旦你重置状态combobox的模型,你也需要选择它的索引。

另一种方法是不选择默认状态或城市,而是提示用户选择一个。 以下是一些使用此方法的代码:

 import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; 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 ); // prevent action events from being fired when the up/down arrow keys are used // mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE); getContentPane().add( mainComboBox, BorderLayout.WEST ); // Create sub combo box with multiple models subComboBox = new JComboBox(); subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // 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); mainComboBox.setSelectedIndex(1); } 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 ) ); } } public static void main(String[] args) { JFrame frame = new ComboBoxTwo(); frame.setDefaultCloseOperation( EXIT_ON_CLOSE ); frame.pack(); frame.setLocationRelativeTo( null ); frame.setVisible( true ); } }