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.
JComponent comp = myTextField;
myScrollPane.getVerticalScrollBar().setValue(comp.getLocation().y-50);
comp.requestFocus();
JComponent comp = myTextField;myScrollPane.getVerticalScrollBar().setValue(comp.getLocation().y-50);comp.requestFocus();
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();
comp.setBackground(new java.awt.Color(255,204,204));