| Author |
Highlighting text in a JTextPane without scrolling to the end.
|
Greg O'Cacher
Greenhorn
Joined: Aug 14, 2007
Posts: 2
|
|
I have some text displayed in a JTextPane that I want to programatically select and highlight. The selection and highlighting works just fine but when the text is selected, the JTextPane scrolls to the end of the selected text. I would like to keep it at the beginning of the selected text. If I call setCaretPosition(start), the beginning of the selected text is displayed but now it is no longer highlighted. public void highlightText(int start,int end){ textPane.grabFocus(); textPane.setSelectionStart(start); textPane.setSelectionEnd(end); /* the following line repositions the text in the window to where I want it but then the highlighting goes away */ textPane.setCaretPosition(start); } Thank you for your solution to this dilemma.
|
 |
Tony Docherty
Bartender
Joined: Aug 07, 2007
Posts: 1176
|
|
|
When you say it scrolls to the end of the selected text would I be correct in assuming that your JTextPane is in a JScrollPane or do you mean something else altogether?
|
 |
Greg O'Cacher
Greenhorn
Joined: Aug 14, 2007
Posts: 2
|
|
Yes, that is correct. It is inside a JScrollPane. -g
|
 |
Brian Cole
Author
Ranch Hand
Joined: Sep 20, 2005
Posts: 852
|
|
Originally posted by Greg O'Cacher: /* the following line repositions the text in the window to where I want it but then the highlighting goes away */ textPane.setCaretPosition(start); }
Yes, setCaretPosition() will clear the selection. If you want to scroll without changing the selection you can instead call scrollRectToVisible(). [note: modelToView() can be helpful for creating the argument to scrollRectToVisible().] You say you want to "programatically select and highlight," but if the "select" part isn't crucial you can highlight only. One way to do this is getHighlighter().addHighlight(start, end, DefaultHighlighter.DefaultPainter).
|
bitguru blog
|
 |
 |
|
|
subject: Highlighting text in a JTextPane without scrolling to the end.
|
|
|