JTable setting model and preserve column formats (width, alignment, etc.)

穿精又带淫゛_ 提交于 2019-11-30 16:30:56

Based on the comments, you could try to add the following method to DbUtils:

public static void updateTableModelData(DefaultTableModel tModel, ResultSet rs) 
        throws Exception {
    tModel.setRowCount(0);
    ResultSetMetaData metaData = rs.getMetaData();

    while (rs.next()) {
        Vector newRow = new Vector();
        for (int i = 1; i <= numberOfColumns; i++) {
            newRow.addElement(rs.getObject(i));
        }
        tModel.addRow(newRow);
    }
}

and then your code would became:

PreparedStatement pst = conn.prepareStatement("SQL Query here");
ResultSet rs = pst.ExecuteQuery();
DbUtils.updateTableModelData((DefaultTableModel) jTable1.getModel(), rs);

too wide question

1) never, really never put 100+ thousand records to the view, and this is valid for all programing languages, is really useless

2) (my view) BeansBindings are out_dated use standard TableModel instead

3) nothing better as @camickr TableFromDatabase is around, or another suggestion is searching for ResultSetTableModel

user3336592

l have discovered that you can create your formatting method and call it after the try block as below.

 private void UpdateTable() throws SQLException {
     String sql = "select * from invoice";
    proDialog.setValue(10);
    table.setShowHorizontalLines(true);
    table.setShowVerticalLines(true);
    proDialog.setValue(20);
    try (
        PreparedStatement pst = con.prepareStatement(sql);

          ResultSet rs = pst.executeQuery();

            )
            {           
        table.setModel(DbUtils.resultSetToTableModel(rs));          
    } catch (Exception e) {
         JOptionPane.showMessageDialog(null, e);
    }
    format();       
}

public void format() {
TableColumnModel m = table.getColumnModel();
m.getColumn(2).setCellRenderer(FormatRenderer.getDateTimeRenderer());
m.getColumn(1).setCellRenderer(FormatRenderer.getTimeRenderer());
m.getColumn(2).setCellRenderer(NumberRenderer.getPercentRenderer());
m.getColumn(4).setCellRenderer(NumberRenderer.getCurrencyRenderer());
m.getColumn(4).setCellRenderer(NumberRenderer.getPercentRenderer());
m.getColumn(5).setCellRenderer(NumberRenderer.getCurrencyRenderer());
}

This will work perfectly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!