我已尝试使用建议的方法,但无法确定如何在建议的操作侦听器中使用操作侦听器…
我想改变第一个组合框的值,并希望下一个组合框在改变时自动更新,类似地,当combobox_1改变时,文本框也会改变…
String[] b = a.getCourseCodes();
final List f = new ArrayList();
final JComboBox comboBox = new JComboBox(b);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String item = comboBox.getSelectedItem().toString();
}
});
comboBox.setEditable(true);
comboBox.setBounds(360, 70, 86, 20);
contentPane.add(comboBox);
JLabel lblStudentName = new JLabel("Student Name");
lblStudentName.setBounds(270, 149, 80, 14);
contentPane.add(lblStudentName);
String[] v = a.getStudentID(comboBox.getSelectedItem().toString());
final JComboBox comboBox_1 = new JComboBox(v);
comboBox_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String item = comboBox_1.getSelectedItem().toString();
}
});
comboBox_1.setBounds(360, 108, 86, 20);
contentPane.add(comboBox_1);
textField_3 = new JTextField();
String y = a.getStudentName(comboBox_1.getSelectedItem().toString());
textField_3.setText(y);
textField_3.setEditable(false);
textField_3.setBounds(360, 146, 86, 20);
contentPane.add(textField_3);
textField_3.setColumns(10);
请帮助编辑代码,这样可以有一个清晰的想法…由于
与其添加一个ItemListener
,不如简单地添加一个ActionListener
,它将在每次更改所选值时触发。然后你可以像这样使用comboBox.getSelectedItem()
:
JComboBox comboBox_1; //you need to declare the comboBox and textField before the ActionListener.
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String[] v = a.getStudentID(comboBox.getSelectedItem().toString());
comboBox_1.setModel(new DefaultComboBoxModel<String>(v));
String y = a.getStudentName(comboBox_1.getSelectedItem().toString());
textField_3.setText(y);
}
});
Add您可以扩展它以在actionPerformed
方法中更改ComboBox
或TextField
的值。
我认为这就是你的意思,尽管我可能错了你的ActionListener
的意图。