Java Tips Weblog

  • Blog Stats

    • 2,572,189 hits
  • Categories

  • Archives

Center Line in Scroll Pane

Posted by Rob Camick on January 4, 2009

Generally, a multi-line text component is added to a scroll pane so that all the lines contained in the text component can be viewed by scrolling through the scroll pane. The caret indicates the current line. When the setCaretPosition() method of the text component is invoked the scroll pane will scroll to make sure the current line is always visible. Therefore, one of three possible scrolling outcomes will occur:

  • no scrolling happens when the current line is within the current viewport of the scroll pane
  • scroll such that the current line is displayed at the top of the scroll pane
  • scroll such that the current line is displayed at the bottom of the scroll pane

There may be times when you wish the current line to be positioned in the center of the scroll pane.

To center the current line you will manually need to set the position of the viewport. To handle this situation a new method has been added to the RXTextUtilities class:

  • centerLineInScrollPane – when possible the line with the caret will be centered in the scroll pane

For example, to display the tenth line of text starting at the center of the scroll pane you would do:

RXTextUtilitites.gotoStartOfLine(textArea, 10);
RXTextUtilitites.centerLineInScrollPane(textArea);

center-line-in-scroll-pane

Get The Code

RXTextUtilities.java

See Also

Text Utilities

Leave a comment