How do I center the Caret position of a JTextPane by autoscrolling?
I would like to auto scroll in my JTextPane so that the line with the caret (which is highlighted) is centered. I am highli开发者_Python百科ghting the line by using the Utilities.getRow(...caretPosition) method. Seems to be a pretty unknown problem. Thanks!
Take a look at Center Line in Scroll Pane. It centers the caret vertically, but it is trivial to also center the caret horizontally.
Here is the code modified so it also centers horizontally:
public static void centerLineInScrollPane(JTextComponent component)
{
Container container = SwingUtilities.getAncestorOfClass(JViewport.class, component);
if (container == null) return;
try
{
Rectangle r = component.modelToView(component.getCaretPosition());
JViewport viewport = (JViewport)container;
int extentWidth = viewport.getExtentSize().width;
int viewWidth = viewport.getViewSize().width;
int x = Math.max(0, r.x - (extentWidth / 2));
x = Math.min(x, viewWidth - extentWidth);
int extentHeight = viewport.getExtentSize().height;
int viewHeight = viewport.getViewSize().height;
int y = Math.max(0, r.y - (extentHeight / 2));
y = Math.min(y, viewHeight - extentHeight);
viewport.setViewPosition(new Point(x, y));
}
catch(BadLocationException ble) {}
}
This is how i adjusted it:
int y = Math.max(0, r.y - (extentHeight / 2));
y = Math.min(y, viewHeight - extentHeight);
int oldY = viewport.getViewPosition().y;
for(int i = oldY;i<y;i++){
viewport.setViewPosition(new Point(0, i));
Thread.sleep(10);
}
精彩评论