我必须有两个组合框,根据第一个组合框的选择,第二个组合框的选定值应更改。
请在下面找到代码片段:
secondcombobox.setSelectedItem(firstcombobox.getSelectedItem());
最佳答案
您应该使用ActionListener:
firstcombobox.addActionListener(new ActionListener(){
void actionPerformed(ActionEvent e){
// sets the selected item of secondcombobox to be the value of firstcombobox
// assuming secondcombobox contains such a value.
secondcombobox.setSelectedItem(firstcombobox.getSelecteditem());
}
});
注意这里的范围界定很重要。您可以将
firstcombobox
和secondcombobox
设置为全局或最终形式,也可以使用稍微不同的形式,其中将这些参数用作构造函数的输入:firstcombobox.addActionListener(new ActionListener(firstcombobox, secondcombobox){
private JComboBox a;
private JComboBox b;
public ActionListner(JComboBox a, JComboBox b){
this.a = a;
this.b = b;
}
void actionPerformed(ActionEvent e){
// sets the selected item of a to be the value of b
// assuming a contains such a value.
b.setSelectedItem(a.getSelecteditem());
}
});