Problem
Due to a rather annoying and very old bug in JTable you will never get a horizontal scrollbar on a JTable even if the table is wider than the JScrollPane you placed it in. According to the bug report this is due to an error in the handling of the autoresize functionality of JTable.
Solution
There are two ways around this: the first and easiest (which may be good enough for most people) is to turn OFF autoresize on your JTable using table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); (where 'table' is a JTable).
The second (more involved) way is to fix the responsible function in JTable (which would involve creating a custom subclass of JTable).
The code that you need is listed (I haven't tried it!) in bug report #1027936
Override JTable.getScrollableTracksViewportWidth() to honor the table's
preferred size and show horizontal scrollbars if that size cannot be
honored by the viewport if an auto-resize mode is selected. Here is
the suggested change:
/**
* Returns false to indicate that horizontal scrollbars are required
* to display the table while honoring perferred column widths. Returns
* true if the table can be displayed in viewport without horizontal
* scrollbars.
*
* @return true if an auto-resizing mode is enabled
* and the viewport width is larger than the table's
* preferred size, otherwise return false.
* @see Scrollable#getScrollableTracksViewportWidth
*/
public boolean getScrollableTracksViewportWidth() {
if (autoResizeMode != AUTO_RESIZE_OFF) {
if (getParent() instanceof JViewport) {
return (((JViewport)getParent()).getWidth() > getPreferredSize().width);
}
}
return false;
}
Could be worth it if you have several JTables in your project or you rely heavily on autoresize.