我目前正在使用CardLayout
和Netbeans GUI构建器使用JAVA和h2数据库创建桌面应用程序。这个应用程序基本上做CRUD操作,用于保存客户数据,购买和产品列表。
我将数据从数据库加载到JTable中,因此当数据增长时,加载时间开始变慢,应用程序似乎冻结或对用户无响应。经过几天的谷歌搜索,我遇到了SwingWorker,Thread,Runnable和EDT(不知道还有什么)。
我在构造函数中运行以下代码。我认为问题出在这里。
private void updateTable() {
Vector<Object> columnNames = new Vector<Object>();
Vector<Object> data = new Vector<Object>();
Connection conn = new DBConnection().connect();
try {
Statement st = conn.createStatement();
String numOfRow = cboNumberOfRow.getSelectedItem().toString();
if (numOfRow == "ALL") {
numOfRow = "-1";
}
String query = "select c.custid as \"id\",c.custname as \"Customer Name\",c.custic as \"IC\",c.custphoneno as \"Tel No.\",e.pointearned as \"Point Earned\", e.totalspent as \"Total Spent\" from customer c join expenses e on c.custid = e.custid group by c.custid limit " + numOfRow;
ResultSet rs = st.executeQuery(query);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++) {
columnNames.addElement(md.getColumnLabel(i)); //md.getColumnName will return original table column name instead from the query itself
}
// Get row data
while (rs.next()) {
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
rs.close();
st.close();
conn.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
DefaultTableModel model = new DefaultTableModel(data, columnNames) {
@Override
public Class getColumnClass(int column) {
switch (column) {
case 1:
return String.class;
case 4:
return Double.class;
case 5:
return Double.class;
default:
return String.class;
}
}
@Override
public boolean isCellEditable(int row, int col) {
return false;
}
};
customerTable.setModel(model); //set custom model
}
希望有人可以指出我的错误,并清楚地了解正确的做法。提前谢谢。