我試圖有兩個Jcombox,其中第二個Jcombox應根據第一個Jcombox中的更改來更改它的值。 我試過但不能成功,任何幫助表示讚賞。由於java JComboBox問題
這是我已經試過到目前爲止:
public class SharedDataBetweenComboBoxSample {
static private String selectedString(ItemSelectable is) {
Object selected[] = is.getSelectedObjects();
return ((selected.length == 0) ? "null" : (String)selected[0]);
}
public static void main(String args[]) {
final String labels[] = { "A", "B", "C" };
final String labelsA[] = { "A", "AA", "AAA" };
final String labelsB[] = { "B", "BB", "BBB" };
final String labelsC[] = { "C", "CC", "CCC" };
final JFrame frame = new JFrame("Shared Data");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JComboBox comboBox1 = new JComboBox();
comboBox1.addItem(labels);
comboBox1.setSelectedItem(null);
final JComboBox comboBox2 = new JComboBox();
// comboBox2.setEditable(true);
panel.add(comboBox1);
panel.add(comboBox2);
frame.add(panel,BorderLayout.NORTH);
ItemListener itemListener = new ItemListener() {
public void itemStateChanged(ItemEvent itemEvent) {
int state = itemEvent.getStateChange();
System.out.println((state == ItemEvent.SELECTED) ? "Selected" : "Deselected");
System.out.println("Item: " + itemEvent.getItem());
ItemSelectable is = itemEvent.getItemSelectable();
System.out.println(", Selected: " + selectedString(is));
if (selectedString(is) == "B") {
comboBox2.addItem(labelsB);
// frame.add(comboBox1, BorderLayout.CENTER);
} else if (selectedString(is) == "A") {
comboBox2.addItem(labelsA);
// frame.add(comboBox1, BorderLayout.CENTER);
} else if (selectedString(is) == "C") {
comboBox2.addItem(labelsC);
// frame.add(comboBox1, BorderLayout.CENTER);
} else {
comboBox2.setSelectedItem(null);
// frame.add(comboBox1, BorderLayout.CENTER);
}
}
};
comboBox1.addItemListener(itemListener);
frame.setSize(300,200);
frame.setVisible(true);
}
}
確定這是一個重複的 – hvgotcodes 2010-11-04 22:38:52
我嘗試了exampledepot.com和java2s.com的一些例子,但我無法根據自己的需要使其工作。 – user234194 2010-11-04 22:40:13
你爲什麼不開始編輯你的發佈和發佈格式正確的代碼。你如何期望我們讀取隨機格式化的代碼。 – camickr 2010-11-04 23:07:10