Reputation: 253
I have a JTable on a JScrollPane. I want that table occupied the entire scroll. So I add this:table.setAutoResizeMode(JTable.AUTO_RESIZE_All_Columns);
It works good when there are only a few columns. But when there are a lot of columns it looks like
that:
As you can see there are too narrow columns. I try to add this code for all columns: table.getColumnModel().getColumn(1).setMinWidth(75);
It works. And I added this code to JScrollPane: setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
But horisontal scroll bar
doesn't work:
You can see it, but it doesn't work. I know that I could solve all my problems with this code:
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF)
But in this case my table doesn't occupied the entire scroll. So, I want that columns extended the full width of the scroll when there are only a few columns and I want that columns are not narrowed to less than a certain value when there are a lot of columns. And I want to have a horizontal scroll bar. Is it possible to do that?
Sorry, it was a silly question. I could to do all what I want with this code:
if (getColumnModel().getColumnCount() > 13)
setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
else
setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
But if somebody kmows more elegant solution show it please. It will be really helpful for me.
Upvotes: 2
Views: 1321
Reputation: 2147
Duplicate.
You can find here 2 elegant solutions.
One of which is:
jTable.getParent().addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent e) {
if (jTable.getPrefer1sredSize().width < jTable.getParent().getWidth()) {
jTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
} else {
jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
}
}
});
Upvotes: 2