我有用于创建表模型的Swingworker,用于在程序启动时更新jTable。但我不知道如何从EDT调用此模型并将此模型应用于我的jtable?
这是我的Swingworker代码;
public class FillTable extends SwingWorker<DefaultTableModel, DefaultTableModel> {
private final DefaultTableModel model;
public FillTable(DefaultTableModel model) {
this.model = model;
}
@Override
protected DefaultTableModel 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);
}
rsaccounts.close();
stmt.close();
model = new DefaultTableModel(data, columnNames);
return model;
}
protected void done() {
try {
TableModel model = get();
} catch (InterruptedException | ExecutionException ex) {
ex.printStackTrace();
}
}
}
下面的方法返回错误; 线程“AWT-EventQueue-0”中的异常java.lang.IllegalArgumentException:无法设置null TableModel
private DefaultTableModel model1;
FillTable fff = new FillTable(model1);
fff.execute();
model1 = fff.model;
jTable3.setModel(model1);
答案 0 :(得分:1)
执行
之类的操作时FillTable fff = new FillTable(model1);
fff.execute();
model1 = fff.model;
jTable3.setModel(model1);
然后行<{1}}很可能在 SwingWorker完成之前执行。 model1 = fff.model
调用将导致工作在后台完成,无论工作是否已完成,都可以执行下一行。
一般方法可能是在execute
方法中使用该模型,大致,如下所示:
done()
(为此,您必须将protected void done() {
try {
TableModel model = get();
jTable3.setModel(model); // Use it here!
} catch (InterruptedException | ExecutionException ex) {
ex.printStackTrace();
}
}
的引用传递给SwingWorker - 也就是说,将其传递给构造函数并将其作为字段存储在SwingWorker中)。
可能有更优雅的解决方案,但基于目前提供的代码,这至少似乎是错误的原因和可能的解决方案。