나는 문제가 국가 목록을로드하지만 내 응용 프로그램을 시작이없는 다른 목록
특별히 선택된 인덱스를 설정해야 할 것 같다 리스너를 호출합니다.
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);
}
}
멋진 솔루션, 감사합니다! – jion