tenten
tenten

Reputation: 1274

Setting column width in JTable in Java

I have created a JTable that retrieves some data from the MySQL database to 2 columns.. For the 2nd column width is not enough.. so i coded below method(Also Includes the data retrieval code from the database)and called it. But the column width is not effected. What is the error 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);
    }

}

Upvotes: 4

Views: 4631

Answers (1)

Stefan
Stefan

Reputation: 2613

list_table.getColumnModel().getColumn(0).setPreferredWidth(20);

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

Anyhow setting the width for a column is using function setWidth()

For 2nd column it is:

columnModel.getColumn(1).setWidth(100);

Upvotes: 4

Related Questions