gpt4 book ai didi

java - 如何更改 JComboBox 的选定值

转载 作者:行者123 更新时间:2023-11-29 04:03:08 25 4
gpt4 key购买 nike

我有两个组合框,基于在第一个组合框中所做的选择,第二个框的选定值应该改变。请在下面找到代码片段:

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

});

注意这里的范围很重要。您可以将 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());
}

});

关于java - 如何更改 JComboBox 的选定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2140280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com