• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Highlighting text in a JTextPane without scrolling to the end.

 
Greg O'Cacher
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2939
59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, that is correct. It is inside a JScrollPane.

-g
 
Brian Cole
Author
Ranch Hand
Posts: 899
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic