Alison Z Alison Z - 18 days ago 6
Java Question

JButton invoked JTable show up in delay

I'm writing a library system that interacts with database currently.
The function I want is: each time I click the JButton "lobBut", the JTable "table" will show the newest content.
Using the following code, I can realize this function. HOWEVER, there is a delay in the showing up of the JTable. To make things weirder, If I click on other applications (such as Chrome or any other), the JTable would show up immediately without delay. Could anyone help me overcome this issue? Thank you!

JButton lobBut = new JButton("List of Books");
lobBut.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent event){
centerPanel.removeAll();
JTable bookTable = new JTable(BookTableModel.getTableModel("SELECT * FROM books"));
JScrollPane pane = new JScrollPane(bookTable);
bookTable.setPreferredScrollableViewportSize(new Dimension(600, 70));
bookTable.setFillsViewportHeight(true);
DefaultTableCellRenderer renderer = (DefaultTableCellRenderer) bookTable.getTableHeader().getDefaultRenderer();
renderer.setHorizontalAlignment(JLabel.CENTER);
bookTable.setShowGrid(true);
bookTable.setGridColor(Color.GREEN);
bookTable.setVisible(true);
centerPanel.add(pane);
}
});


Here is the BookTableModel class:

public class BookTableModel extends AbstractTableModel{
private String[] columnNames = {};
private Object[][] data = {};

public int getColumnCount(){
return columnNames.length;
}

public int getRowCount(){
return data.length;
}

public Object getValueAt(int row, int col){
return data[row][col];
}

public String getColumnName(int col){
return columnNames[col];
}

public Class getColumnClass(int c){
return getValueAt(0, c).getClass();
}

public static DefaultTableModel getTableModel(String sql){
try(
Statement stmt = ConnectionManager.getInstance().getConnection().createStatement();
ResultSet rs = stmt.executeQuery(sql);
){
ResultSetMetaData metaData = rs.getMetaData();
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for(int column = 1; column <= columnCount; column++){
columnNames.add(metaData.getColumnName(column));
}

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


}catch(SQLException e){
System.err.print(e);
return null;
}
}


}

Answer

add

    centerPanel.updateUI();

after

    centerPanel.add(pane);
Comments