I am currently creating a desktop application using JAVA and h2 database using CardLayout
and Netbeans GUI builder. This app basically do CRUD operation and used to save customer data, purchases and list of products.
I load the data from database into a JTable so when data grows, the loading time begin to slow down and the application will seems to be froze or unresponsive to the user. After few days of googling, I have came across to SwingWorker, Thread, Runnable and EDT(not sure what else more).
I run the codes below in the constructor. I think the problem is here.
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
}
Hope someone can point out my mistakes and clear picture of doing it correctly. Thanks in advance.