gpt4 book ai didi

java - 检查 JComboBox 值

转载 作者:搜寻专家 更新时间:2023-10-30 23:14:16 24 4
gpt4 key购买 nike

我需要创建一个新方法来检查组合框中所选项目的值。该组合框是从数据库中填充的。

这是获取选中项的方法:

 combo.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {

String x=(String) combo.getSelectedItem();

字符串“x”保存了所选项目的值,因为我需要在我的其他查询中使用“x”。

    ResultSet st = stt.executeQuery("Select Name from Table where Number="+x+"");

通过该查询,我可以填充 JList

问题是,当我在组合框中选择另一个项目时,列表不会更新。所以我需要创建另一个语句来检查组合框值吗?如果是,如何?

最佳答案

让您的 JList 使用同样实现了 ActionListenerListModel。将这个专门的监听器添加到组合中。每次组合更改时,您的 ListModel 的 Action 监听器都会被调用。在监听器中,您可以就地更新 ListModel

附录:这是基本方法。

enter image description here

/**
* @see http://stackoverflow.com/a/16587357/230513
*/
public class ListListenerTest {

private static final String[] items = new String[]{"1", "2", "3"};
private JComboBox combo = new JComboBox(items);
private JList list = new JList(new MyModel(combo));

private static class MyModel extends DefaultListModel implements ActionListener {

private JComboBox combo;

public MyModel(JComboBox combo) {
this.combo = combo;
addElement(combo.getSelectedItem());
combo.addActionListener(this);
}

@Override
public void actionPerformed(ActionEvent e) {
set(0, combo.getSelectedItem());
System.out.println("Combo changed.");
}
}

private void display() {
JFrame f = new JFrame("ListListenerTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(1, 0));
f.add(combo);
f.add(list);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ListListenerTest().display();
}
});
}
}

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

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