所以这是我的问题:我目前正在使用两个 JComboBoxes。第二个 JComboBox 应该根据第一个 JComboBox 中选择的内容进行更新。在这种情况下,第一个 JComboBox 包含学习专业的首字母:(ART、CSC、MTH、PHY 等),第二个 JComboBox 应该更新为该特定专业存在的所有可能的班级编号。所以我拥有的文件阅读器能够读取所有信息并相应地填写两个列表。当从第一个 JComboBox 中选择特定专业时,我遇到的第一个问题是进行第二次 JComboBox 更新。我通过向第一个 JComboBox 添加一个 actionListener 来解决这个问题。但现在我有另一个问题..:
问题:当我单击第一个 JComboBox 时,有一个应该有的所有专业的列表,但是当我单击其中一个专业时,它不会改变。第二个 JComboBox 会适当地改变,就好像我选择了正确的一样,但第一个 JComboBox 不会改变。它只是停留在“ART”(按字母顺序排列在列表中的第一个)。
我从第一个 JComboBox 中选择其他选项之一:http: //imageshack.us/photo/my-images/845/problem2t.jpg/
它适当地改变了第二个 JComboBox 但第一个没有改变。 http://imageshack.us/photo/my-images/189/problem1n.jpg/
这是我的代码: 首先我有设置图形的构造函数。然后我有我的动作监听器(JComboBox 是最后一个 elseif 语句),然后我有设置 JComboBoxes 的方法。
public Student(){
//Window Attributes
setSize(WINDOW_WIDTH,WINDOW_HEIGHT);
setTitle("Academic Major Selection");
//Center the Program Window
Dimension dim = new Dimension(toolkit.getScreenSize());
setLocation((int)dim.getWidth()/2 - WINDOW_WIDTH/2,(int)dim.getHeight()/2 - WINDOW_HEIGHT/2);
//do not allow resizing of window
setResizable(false);
//create arrays for classes
//input file reader here
String[] subjectArray = {"CSC","MTH","ENG","THE","PHY"};
String[] numberArray = {"100","200","300","400","500"};
//create boxes for dropdown
subjectBox = new JComboBox(subjectArray);
subjectBox.addActionListener(this);
numberBox = new JComboBox(numberArray);
//creates a panel for our dropdown panels
selectPanel = new JPanel();
selectPanel.setLayout(new GridLayout(1,2,25,0));
selectPanel.add(subjectBox);
selectPanel.add(numberBox);
.
.
.//trimmed out some excess stuff
.
try {
setDropDownBoxes();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//show the window
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
//What button is pressed?
.
.
.//Trimmed out some extra stuff
.
//This will equal true when something is selected from the first JComboBox
}else if(((String)subjectBox.getSelectedItem()).length() == 3){
System.out.println("New Subject Selected");
try {
setDropDownBoxes();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
void setDropDownBoxes() throws IOException{
int j=0;
String[][] someArrayTwoD = studentWriter.fetchClassLists();
String[] subjectArray = new String[someArrayTwoD.length];
while(j<someArrayTwoD.length){
subjectArray[j] = someArrayTwoD[j][0];
j++;
}
String[] numberArray = new String[someArrayTwoD[subjectBox.getSelectedIndex()].length-1];
for(int i=0; i<numberArray.length; i++){
numberArray[i] = someArrayTwoD[subjectBox.getSelectedIndex()][i+1];
}
selectPanel.remove(subjectBox);
selectPanel.remove(numberBox);
subjectBox = new JComboBox(subjectArray);
numberBox = new JComboBox(numberArray);
selectPanel.add(subjectBox);
selectPanel.add(numberBox);
selectPanel.validate();
subjectBox.addActionListener(this);
}