gpt4 book ai didi

java - 从 Swingworker 线程填充 jTable

转载 作者:行者123 更新时间:2023-12-01 18:36:06 27 4
gpt4 key购买 nike

我无法从 SwingWorker 线程更新我的 JTable。我的代码;

public class FillTable extends SwingWorker<Void, Void> {

protected Void doInBackground() throws Exception {
ResultSet rsaccounts;
Statement stmt;
String queryaccounts = "select NAME from acc (nolock)\n" + "order by Name";

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://192.100.100.23;" + "databaseName=Dbacc;" + "user=" + "sa" + ";" + "password=" + "sapassword!" + ";";
Connection con = DriverManager.getConnection(connectionUrl);
stmt = con.createStatement();
rsaccounts = stmt.executeQuery(queryaccounts);
ResultSetMetaData rsmd = rsaccounts.getMetaData();


Vector<String> columnNames = new Vector<String>();
columnNames.add(rsmd.getColumnName(1));
System.out.println(columnNames);
int columnCount = rsmd.getColumnCount();

Vector<Vector<Object>> data = new Vector<Vector<Object>>();

while (rsaccounts.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rsaccounts.getObject(columnIndex));
}
data.add(vector);

}
DefaultTableModel model = new DefaultTableModel(columnNames,data);
jTable3.setModel(model);

rsaccounts.close();
stmt.close();
return null;

}
public void done() {
SearchButton.setEnabled(true);
CreateButton.setEnabled(true);
}

}

我在 GUI 的 init 组件中执行此 swingworker 线程,以便在程序启动时填充 jtable。

fillAccList = new FillTable();
fillAccList.execute();

当程序启动时,我在屏幕上看到[NAME],因为我添加了这一行 System.out.println(columnNames);如您所见,用于控制 Swing worker 。但我的jtable没有填满。有什么想法吗?

最佳答案

DefaultTableModel 的构造函数首先需要数据,然后是列名称。

更改:

DefaultTableModel model = new DefaultTableModel(columnNames,data);

致:

DefaultTableModel model = new DefaultTableModel(data, columnNames);

关于java - 从 Swingworker 线程填充 jTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21947205/

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