Java – How to scroll to a particular component in jScrollPane and gain focus

Pragmatically scrolling to a particular point in jScrollPane can be tricky, particularly if you have nested panels or layered panes. Here’s a piece of code I find myself using time and time again to have a jScrollPane scroll to a particular element and give it focus on screen.

1. Declare a JComponent and assign it the element requiring focus
JComponent comp = myTextField;
2. Adjust the vertical scroll bar to bring the component into view on screen. This is achieved by determining the Y location of the component in the scrollPane.
myScrollPane.getVerticalScrollBar().setValue(comp.getLocation().y-50);
I reduce the scroll integer value by 50 in my example to ensure the component is fully visible on screen.
3. The component is now visible on screen, so time to give focus.
comp.requestFocus();
Lets put it all together to scroll to, then give focus to, a particular component in a swing application contained in a jScrollPane.
JComponent comp = myTextField;
myScrollPane.getVerticalScrollBar().setValue(comp.getLocation().y-50);
comp.requestFocus();
If your swing application contains nested views in the scrollPane then you must call the getParent() method to move up the chain of views and establish the required scroll position.

Using the example above, lets say myTextField is contained in a jPanel, which itself is contained in the jScrollPane with an unknown Y position greater than 0.

The following code determines the Y position of the jPanel relative to the scrollPane as well as the Y position of myTextField relative to the jPanel. Sum the two values to set the scroll position.

myScrollPane.getVerticalScrollBar().setValue(comp.getParent().getLocation().y + (comp.getLocation().y – 50));
JComponent comp = myTextField;
myScrollPane.getVerticalScrollBar().setValue(comp.getParent().getLocation().y + (comp.getLocation().y – 50));
comp.requestFocus();
Next Steps…
You can manipulate the comp object’s visual properties to give the user prompts as to which field on the form has focus. I use this method to indicate a field that has failed form validation:
comp.setBackground(new java.awt.Color(255,204,204));

JAVA – Set The Position Of The ScrollBar In JScrollPane()



The following codes assumes that you have created a JScrollPane() called scrollPane


int x = 0;
int y = 10;

scrollPane.getViewport().setViewPosition(new java.awt.Point(x, y));





In this example x sets the horizontal position of a horizontal scroll bar.
y sets the vertical position of a vertical scroll bar – in this case the vertical scroll bar will appear 10 pixels down from the top.