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.


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.

cwarn23 commented: thank you times 1 million. Solved my problem with a short deadline +12

Hi everyone,

Hmm 1998. Now its 2005. Seven years. Makes you wonder if that bug will be fixed.

Richard West

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.