JCombobox改变了另一个JCombobox
我正在尝试组合2个jcomboboxes。 1个combobox用于显示类别的开销。 第二个combobox是从文本文件中读取文件以显示产品类型。 如果我改变第一个combobox,我希望第二个combobox将根据用户在第一个combobox中选择的内容而改变。
我还有机会从文本文件中加载其他combobox吗? 这个子项目不是Arrays,但与之前一样,因为它位于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(); } }
例如
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class ComboBoxTwo extends JFrame implements ActionListener, ItemListener { private static final long serialVersionUID = 1L; private JComboBox mainComboBox; private JComboBox subComboBox; private Hashtable
首先,不要将字符串与==进行比较,而是使用equals或equalsIgnoreCase方法。 例如,
改变这个:
if (item == "Groceries") {
对此:
if ("Groceries".equalsIgnoreCase(item.toString())) {
您需要在item上调用toString()以确保将String与String进行比较。 在执行任何此操作之前,您还需要确保该项不为null。
if(jComboBox1.getSelectedItem() == "First Choice"){ jComboBox2.removeAllItems(); jComboBox2.addItem("First Choice Item 1"); } if(jComboBox1.getSelectedItem() == "Another Choice"){ jComboBox2.removeAllItems(); jComboBox2.addItem("Another Choice Item 1"); }
或者你可以在数组中包含太多的项目。