JScrollPane : Java Glossary
Allows you to display part of a large JPanel and let the
user scroll to see all over it. In AWT (Advanced Windowing Toolkit),
you use ScrollPane, and in Swing JScrollPane. There
- Add the contents to be scrolled in the JScrollPane constructor. Don’t add
it later the way you do with ScrollPane. For some
reason, if you add it later, all you see then is a
blank panel, even though all the code appears to paint normally. You can however
add/change it later with setViewportView.
- You can freeze a non-vertically-scrolling header with setColumnHeader or setColumnHeaderView
just like a spreadsheet. There are analogous features for
non-horizontally-scrolling row headers.
- You can control what is visible with by getting the horizontal or vertical
JScrollBar and using setValue.
- JScrollPane lets you independently control whether
there are vertical or horizontal scroll bars, unlike AWT
ScrollPane which requires both to be set the same
Here is how to make the most recently written part of a
Here is how to make a row of JTable visible in the scroll
final Rectangle r = jTable.getCellRect( rowIndex, colIndex, true );
if ( r != null )
jTable.scrollRectToVisible( r );
- There is a setViewPosition method defined for
JScrollPane, JComponent (of
the component being scrolled) and Viewport. Each behaves
- To scroll back to the top,
does nothing. You must use
instead or JTable.scrollRectToVisible.
Oracle’s Javadoc on JScrollPane
class : available:
Fighting over the Scroller
Any program that uses JScrollPane has a potential
problem if it ever sets the position of the scroll using one of the techniques above.
The user may also be trying to scroll at the same time. The program should defer to
the user, e.g. if the user has recently moved the scroll, or is holding the thumb bar
with mouse right now, defer the scroll move to later, and ignore it entirely if there
is another scroll setting. This logic properly belongs in JScrollPane. I wonder if anyone has ever tackled this problem or wants
to. There might even be a way to introduce and enhanced JScrollPane into arbitrary
programs unaware of the problem, with a L&F.