• 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:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

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: 3321
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
Posts: 965
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).
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!