3

I am trying to highlight a specific lines from JTextPane. Suppose I want to highlight the 5th line from JTextPane, how do I get the indexOf it to highlight it if the lines are same?

Example content of JTextPane, I want to higlight 5th and 11th line from below lines,

This text is from stackoverflow
This text is from stackoverflow
This text is from stackoverflow
This text is from stackoverflow
This text is from stackoverflow
This text is from stackoverflow
This text is from stackoverflow
This text is from google
This text is from yahoo
This text is from yahoo
This text is from yahoo
This text is from yahoo

Code:

//Code to highlight
//text is jtextpane
final static Color HILIT_COLOR = Color.LIGHT_GRAY;
DefaultHighlighter hilit = new DefaultHighlighter();
DefaultHighlightPainter painter = new  
    DefaultHighlighter.DefaultHighlightPainter(HILIT_COLOR);
text.setHighlighter(hilit);

hilit.removeAllHighlights();
String s = text.getText();
try {
    hilit.addHighlight(0, 10, painter);
} catch (BadLocationException ex) {
    Logger.getLogger(TextLines.class.getName()).log(Level.SEVERE, null, ex);
}
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
FirmView
  • 3,130
  • 8
  • 34
  • 50

2 Answers2

3

1) hilit.removeAllHighlights(); doens't works correctly in all of cases, you have fill arrays of Highlighter[],

2) you have extract Document (Model for JTextComponents) from JTextComponents, tutorial talking about searching in the Document, then you can styled text into JTextPane(I'm talking about easiest way, there are ways how to determine contents in the concrete row(s), those things could be complicating the resize of JTextComponents)

3) I leaving answer about Columns and Rows from JTextComponents for @Stanislav

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • +1 for your effort. Still waiting for getting the indexOf repeating line contents – FirmView Mar 20 '12 at 01:16
  • I _think_ you'd have to use a [`DocumentListener`](http://docs.oracle.com/javase/tutorial/uiswing/events/documentlistener.html) to keep track of the line boundaries (offset & length) as they are inserted. – trashgod Mar 20 '12 at 01:42
  • +1 I think you know all the row/columns related code as well:-) Use Javax.text.Utilities.getRowStart()/getRowEnd() – StanislavL Mar 20 '12 at 05:30
3

I'm guessing your model is HTMLDocument, which isn't really line oriented. Alternatively, consider a JList and custom renderer using JTextPane.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • +1 for your suggestion. Still waiting for getting the indexOf repeating line contents – FirmView Mar 20 '12 at 01:18
  • I'm advocating the use of a container that has a line-oriented selection model, but I've commented on my understanding of @mKorbel's [approach](http://stackoverflow.com/a/9778570/230513). – trashgod Mar 20 '12 at 05:16