Win a copy of The Journey To Enterprise Agility this week in the Agile and Other Processes forum! And see the welcome thread for 20% off.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

Highlighting text in a JTextPane without scrolling to the end.  RSS feed

 
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.
 
Bartender
Posts: 3320
86
  • 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
 
Author
Ranch Hand
Posts: 964
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
Boost this thread!