gpt4 book ai didi

java - 动态 JComboBox

转载 作者:太空宇宙 更新时间:2023-11-04 14:13:38 24 4
gpt4 key购买 nike

我有以下数据(字符串):

Course1: A1
Course1: A2
Course2: B1
Course2: B2
Course2: B3
Course2: B4
Course3: C1
Course3: C2

我想创建两个JComboBox(JComboBox1、JComboBox2),以便JComboBox1包含Course1、Course2、Course3等。

如果我从 JComboBox1 选择 Course2,则应在 JComboBox2 中填充相应的 B1、B2、B3、B4。

如何实现这个?非常感谢。

最佳答案

是的,只需创建一个 DefaultComboBoxModel对于每个集合,当 JComboBox1 更改时,对 JComboBox2 执行 setModel()

附录:例如,

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class ComboTest extends JPanel implements ActionListener, Runnable {

private final JComboBox combo1 = new JComboBox(
new String[]{"Course 1", "Course 2", "Course 3"});
private final JComboBox combo2 = new JComboBox();
private ComboBoxModel[] models = new ComboBoxModel[3];

public ComboTest() {
models[0] = new DefaultComboBoxModel(
new String[]{"A1", "A2"});
models[1] = new DefaultComboBoxModel(
new String[]{"B1", "B2", "B3", "B4"});
models[2] = new DefaultComboBoxModel(
new String[]{"C1", "C2"});

combo2.setModel(models[0]);
this.add(combo1);
this.add(combo2);
combo1.addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent e) {
int i = combo1.getSelectedIndex();
combo2.setModel(models[i]);
}

@Override
public void run() {
JFrame f = new JFrame("ComboTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}

public static void main(String[] args) {
EventQueue.invokeLater(new ComboTest());
}
}

关于java - 动态 JComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27999882/

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