我想2個jcomboboxes結合起來。 1組合框用於顯示費用類別。第二個組合框是從文本文件中讀取文件以顯示產品的類型。如果我更改第一個組合框,我希望第二個組合框將根據用戶在第一個組合框中選擇的內容進行更改。JComboBox的另一個變化JComboBox的
是否有任何機會,我仍然可以從文本文件加載其他組合框?該子項不會是數組,而是與之前相同,因爲它位於cboperson的代碼底部。
編輯的代碼:
private JComboBox cboCategory;
private JComboBox cboPerson;
private JComboBox cboItem;
public String itemChange = "groceries.txt";
public ExpenditureTracker() {......
String[] items = {"Select Item", "Groceries", "Bills", "Travelling", "Leasure", "Other"};
mainComboBox = new JComboBox(items);
mainComboBox.addActionListener(this);
mainComboBox.addItemListener(this);
//prevent action events from being fired when the up/down arrow keys are used
//mainComboBox.putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE);
mainComboBox.setBounds(113, 138, 85, 20);
importPanel.add(mainComboBox);
subComboBox = new JComboBox();// Create sub combo box with multiple models
subComboBox.setPrototypeDisplayValue("XXXXXXXXXX"); // JDK1.4
subComboBox.addItemListener(this);
subComboBox.setBounds(113, 188, 85, 20);
importPanel.add(subComboBox);
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);
String[] subItems4 = {"Select Fruit", "Apple", "Orange", "Banana"};
subItems.put(items[4], subItems3);
String[] subItems5 = {"Select Fruit", "Apple", "Orange", "Banana"};
subItems.put(items[5], subItems3);
loadDataTocboPerson();
}
private void loadDataToCboPerson() {
Scanner fileReader = new Scanner(getClass().getResourceAsStream(
itemChange));
try {
DefaultComboBoxModel model = new DefaultComboBoxModel();
while (fileReader.hasNextLine()) {
model.addElement(fileReader.nextLine());
}
cboItem.setModel(model);
} finally {
fileReader.close();
}
}
你調用loadDataToCboItem()?你應該在displaySelectedItem()方法中從你的actionPerformed方法中調用它。 – 2011-06-05 21:52:12
請再編輯你的答案。代碼格式不正確,不清楚這些方法屬於哪個組合框。 – toto2 2011-06-05 21:54:36