gpt4 book ai didi

java - 如何使 JCombobox 具有更改其他 JCombobox 上的项目的功能

转载 作者:行者123 更新时间:2023-12-01 06:46:47 25 4
gpt4 key购买 nike

我的转换器程序中有 3 个 JCombobox,其中一个用于类别,两个用于选择要执行的功能;我希望程序做的是,当用户在一个 JCombobox 中选择一个类别时,两个 JCombobox 将自动更改与所选类别相关的内容(请帮助我使用 JCombobox 更改项目的功能,当选择一个类别时,其他更改值);

最佳答案

JB Nizet说,这是一个简短的例子:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class ConnectedComboBoxDemo extends JFrame implements ActionListener {

private static final long serialVersionUID = 6108579736224814080L;

private JPanel panel;
private JComboBox combo1;
private JComboBox combo2;

public ConnectedComboBoxDemo() {
panel = new JPanel();
String[] combo1Item = new String[]{"val1", "val2", "val3"};
combo1 = new JComboBox(combo1Item);
combo1.addActionListener(this);

String[] combo2Item = new String[]{"val11", "val12", "val13"};
combo2 = new JComboBox(combo2Item);

panel.setLayout(new BorderLayout());
panel.add(combo1, BorderLayout.WEST);
panel.add(combo2, BorderLayout.EAST);

setContentPane(panel);
pack();
setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
String selectedValue = combo1.getSelectedItem().toString();
String[] combo2Item = null;

DefaultComboBoxModel model = (DefaultComboBoxModel) combo2.getModel();
model.removeAllElements();

if(selectedValue.equals("val1")){
combo2Item = new String[]{"val11", "val12", "val13"};
} else if(selectedValue.equals("val2")){
combo2Item = new String[]{"val21", "val22", "val23"};
} else if(selectedValue.equals("val3")){
combo2Item = new String[]{"val31", "val32", "val33"};
}

for(String val : combo2Item){
model.addElement(val);
}
}

public static void main(String... args){
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
new ConnectedComboBoxDemo();
}
});
}
}

希望这对您有帮助。

关于java - 如何使 JCombobox 具有更改其他 JCombobox 上的项目的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9553233/

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