Scrolling a Form
Posted by Rob Camick on May 9, 2010
It is easy to create a form, you just create a panel and add some components to it. It is also easy to make the form scrollable, you just add the panel to a scroll pane. However, maybe you’ve noticed that as you tab from component to component the viewport of the scroll pane does not scroll automatically when the focused component is no longer in the viewport? In many cases the form would be more usefull to the user if it would scroll automatically as focus changes from component to component.
Adding an automatic scrolling feature can be implemented in two basic steps:
- handle focus changes – we need to listen for focus changes but we don’t want to add a FocusListener to every component on the form. In this case we can use a tip from the “Global Event Listeners” entry and use the KeyboardFocusManager to listen for focus changes.
- scroll the viewport – this is done by using the scrollRectToVisible(…) method of JComponent. All we need to do is determine the Rectangle values to be used by the scroll method.
The FormScroller class will manage these two steps for you. There are only a couple of properties you can set to control the behaviour of the scroller. First, you can control the scroll type by using the setType(…) method:
- Type.COMPONENT (default) – the component that has focus should be visible in the viewport.
- Type.PARENT – the parent Container of the component that has focus should be visible in the viewport. If the Container does not fit completely in the viewport, then Type.COMPONENT scrolling will be used.
- Type.CHILD – the child Container of the viewport view component which contains the focused component should be visible in the viewport. If the child Container does not fit completely in the viewport then Type.PARENT scrolling will be used.
Additionally, you may want to specify scrolling insets by using the setScrollInsets(…) method. Normally, when the scrollRectToVisible() method is invoked the viewport will be positioned such that the edges of the component are against the edges of the scroll pane. Specifying the scrolling insets will allow a gap between the component and the scroll pane whenever possible.
Well, thats all there is to say about the FormScroller. The image below gives you an idea what the form will look like when you scroll to the first non visible component. The viewport has been moved so the component is positioned 5 pixels above the scroll pane.
In the Webstart demo below, automatic scrolling was added to the scroll pane using:
FormScroller scroller = new FormScroller( scrollPane );
scroller.setScrollInsets( new Insets(5, 0, 5, 0) );
Try The Demo
– Using Java™ Web Start (JRE 6 required)

André Uhres said
Thanks, very useful class. Works fine, my congratulations for this great achievement.
Rob Camick said
Thanks André.