Search code examples
javaswingjtablejscrollpane

Why does the horizontal scrollbar never show up on JTable?


Since a picture is worth a thousand words:

JTable when Horizontal ScrollBar is not needed JTable when Horizontal ScrollBar is needed

I have JTable inside a JScrollPane, and currently the table has 10 columns. Each column is given a minimum width (given by setMinWidth(...)).

First picture: When the JFrame is stretched beyond the sum of all of the minimum widths of all columns then the columns are stretched to fill the window: this is the desired effect (do not want empty space at far right of frame).

Second picture: However when the JFrame is set to a size smaller than this combined minimum size, the horizontal bar does not show up properly and it becomes impossible to view the far right columns. Currently I have JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS as the horizontal bar option hince why for both pictures the horizontal bar container (appropriate name?) is there, but the actual bar itself never shows up. If I have JScrollPane.HORIZONTAL_SCROLLBAR_OFF, the horizontal bar container never shows.

Vertical works fine btw.

I have tried many things, including disabling auto resizing and trying to set the column widths myself when the JScrollPane width exceeds the min width sum of the columns. It doesn't seem right that I would have to do that manually myself. I can provide my code if necessary, but I don't think that it is necessary because it's just a JScrollPane hosting a JTable.


Solution

  • The solution was to overwrite the getScrollableTracksViewportWidth() method:

    @Override
    public boolean getScrollableTracksViewportWidth() {
      return (getPreferredSize().width < getParent().getWidth());
    }