2

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.

1 Answers1

2

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);
        }
    }
});
Community
  • 1
  • 1
Leet-Falcon
  • 2,107
  • 2
  • 15
  • 23
  • Thank you very much! It's really good! But now I have another problem. In my implementation of JTable I override method prepareRenderer because I want to have columns that stretched for content. And it worked good. But now it doesn't work because of this code: jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); Is it possible to solve this problem? – Александр Елизаров Nov 30 '15 at 10:51
  • @Александр Елизаров Open a new question and submit the code of prepareRenderer – Leet-Falcon Nov 30 '15 at 15:16
  • I already do it. Here is my question with code: http://stackoverflow.com/questions/33999145/how-to-stretch-columns-in-jtable-by-content – Александр Елизаров Nov 30 '15 at 15:19