gpt4 book ai didi

java - 当 JTable 中的数据更改时,ComboBox 不刷新

转载 作者:行者123 更新时间:2023-12-02 04:52:07 25 4
gpt4 key购买 nike

我正在尝试开发一个小应用程序,其中有一个 JComboBox,它在开始时使用从 JTable 检索的一些元素进行初始化。由于插入不同的数据,JTable 将不断变化。

但是,每当我向数据库插入新数据或将其删除时,组合框不会更新,只有当我关闭程序并打开它时才会更新。谁能给我提示/帮助我做错了什么。

这是我的代码:

private void fillcombopart() {

try {
String sql = "select * from partrepair";
conn = DriverManager.getConnection("jdbc:sqlite:C:\\database.db");
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
DefaultComboBoxModel model12 = new DefaultComboBoxModel();

while (rs.next()) {

model12.addElement(rs.getString("Name"));
model12.addListDataListener(partCombo);
}
partCombo.setModel(model12);
// partCombo.addItem(rs.getString("Name"));


pst.close();
rs.close();

} catch (Exception e) {
e.printStackTrace();
}

数据库更新方法

public void refresh2() {
try {
String sql12 = "select * from partrepair";
conn = DriverManager.getConnection(s);
PreparedStatement pst12 = conn.prepareStatement(sql12);
ResultSet rs = pst12.executeQuery();
tablerepair.setModel(DbUtils.resultSetToTableModel(rs));
pst12.close();
rs.close();

} catch (Exception e) {
e.printStackTrace();
}
}

最佳答案

Whenever i insert new data to the database or remove it, the combobox does not update, only when i close the program and open it. Could anyone give me a hint/ help of what i am doing wrong.

您似乎只设置了 JComboBox 的模型一次,之后就不再更新它,或者即使您这样做了,也不会向我们展示。该模型不会神奇地改变——如果数据库的数据发生变化,您必须编写代码来更改它。这意味着您必须以某种方式监听数据库的更改,然后当发生这种情况时,更新 JComboBox 的模型。

关于java - 当 JTable 中的数据更改时,ComboBox 不刷新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29133625/

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