如何更改JComboBox的选定值

时间:2010-01-26 15:15:43

标签: java swing

我需要两个组合框,根据第一个组合框中的选择,第二个框的选定值应该改变。 请在下面找到代码段:

secondcombobox.setSelectedItem(firstcombobox.getSelectedItem());

4 个答案:

答案 0 :(得分:2)

您应该使用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());
    }

});

注意这里的范围很重要。您可以将firstcomboboxsecondcombobox设为全局或最终,也可以使用稍微替代的形式,将这些参数作为构造函数的输入:

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());
    }

});

答案 1 :(得分:1)

只有第一个JComboBox中的所选项目也存在于第二个JComboBox中时,您的上述代码才有效;换句话说,与第一个ComboBoxModel中的所选项目进行比较时,第二个true返回JComboBox中存在一个对象。

如果所选项目不在列表中,则方法调用将无效,这可能是您所遇到的情况。

答案 2 :(得分:1)

如果您的两个组合框共享相同的值,则应为它们使用相同的模型。它比使用ActionListener更清晰。

DefaultComboBoxModel model = new DefaultComboBoxModel();
combo1.setModel(model);
combo2.setModel(model);

//init your values in the combo here

然后,当您在其中一个组合框中选择一个项目时,它将在另一个组合框中被选中。

答案 3 :(得分:0)

虽然您的最小问题长度使您的问题变得隐蔽,但您可能需要:

firstcombobox.addActionListener() {
 // Do something with secondcombobox
}
相关问题