我在启动应用程序时遇到问题,它会加载国家列表,但不会加载其他列表
似乎您必须专门设置选定的索引才能调用侦听器。
jComboBoxCountries.setModel(...)jComboBoxCountries.setSelectedIndex(0);
通过选择一个国家,国家列表而不是城市列表被收费。
我想这是同样的问题,一旦重置状态组合框的模型,就需要选择其索引。
另一种方法是不选择默认州或城市,而是提示用户选择一个州或城市。这是一些使用这种方法的代码:
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 ); }}


