Pindub_Amateur
Pindub_Amateur

Reputation: 328

JTable setPreferredWidth causing an extra column

This is my code

JTable table = new JTable(attributeValues, attributeNamesString);

table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

for(int z=0;z<table.getColumnCount();z++){
    table.getColumnModel().getColumn(z).setMinWidth(100);
    table.getColumnModel().getColumn(z).setMaxWidth(100);
    table.getColumnModel().getColumn(z).setPreferredWidth(100);
}

Unfortunately, when I run this, I get an additional column on the screen which stretches to the window size. I'm not sure where it's come from or how to fix it.

enter image description here

Upvotes: 0

Views: 192

Answers (1)

EvenLisle
EvenLisle

Reputation: 4812

Are you sure this is caused by the table.getColumnModel().getColumn(z).setPreferredWidth(100); call? I suspect (although I haven't tried it myself) that it is more likely caused by table.getColumnModel().getColumn(z).setMaxWidth(100);, as this sets the columns' maximum width (adding up to 4 x 100px in your case) while the table itself is stretched to more than 4 x 100px.

If you do not want the table itself to be wider than 4 x 100px, can you not set the maximum size of the table as well (http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#setMaximumSize(java.awt.Dimension))?

Upvotes: 1

Related Questions