Monday, 4 June 2012

JScrollPane Repainting Problems

I was having some problems with the JScrollPane not repainting my custom component properly when scrolling.  The results were that the area that was now visible because of the scroll was painted unevenly and looked blurred.  This seems to happen when a component is doing some custom rendering inside a JScrollPane and using the clip to find out what area it should paint.  To fix this call the following methods on your JScrollPane:

scrollpane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);

In the modern swing implementation there is some 'clever' caching of the content view to improve performance which seems to be the problem.  Setting SIMPLE_SCROLL_MODE will force the scroll pane to repaint it's entire contents while scrolling.  Although this is less performant, it at least shows the correct results with minimum fuss.