Setting column width in JTable in Java

I created a JTable that retrieves some data from a MySQL database in 2 columns. For the second column width is not enough. So I coded below the method (also includes code to extract data from the database) and called it, But the column width is not executed. What is the mistake here?

private void updateTable(){

    try {
        //getting data from the mysql database
        String sql = "SELECT ItemID,ItemName FROM druginfo";
        pst=conn.prepareStatement(sql);
        rs=pst.executeQuery();
        list_table.setModel(DbUtils.resultSetToTableModel(rs));
        // resizing the column width
       list_table.getColumnModel().getColumn(0).setPreferredWidth(20);
       list_table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null, "Error : "+ex);
    }

}
+4
source share
1 answer
list_table.getColumnModel().getColumn(0).setPreferredWidth(20);

First you set only PreferredWidth to your first column, not the second. Do you also want preferredWidth for the second? Then you need to call the 2nd column.

Anyway, setting the width for the column uses the function setWidth()

For the second column, this is:

columnModel.getColumn(1).setWidth(100);
+4
source

Source: https://habr.com/ru/post/1599481/


All Articles