3

I am trying to highlight multiple lines of a JTextArea subclass (not selected). Although I want to highlight the whole line and not just the text each line contains. I got this working but it only highlights text :

DefaultHighlighter h = (DefaultHighlighter)textArea.getHighlighter(
    try {
            int start = textArea.getLineStartOffset(blockedLine);
            int end = textArea.getLineEndOffset(blockedLine);
            DefaultHighlightPainter redHighlight = new DefaultHighlighter.DefaultHighlightPainter(Color.RED);
            h.addHighlight(start, end, redHighlight);
        } catch (BadLocationException ex) {
            Logger.getLogger(JavaFilter.class.getName()).log(Level.SEVERE, null, ex);
        }

How can I highlight the whole line instead of just the text ? I am using an open source library for the text area so getting a JTextPane or other component is not an option (using rysntaxtextarea library).

Giannis
  • 5,286
  • 15
  • 58
  • 113
  • 1
    Your code works for me using JDK6_7 on XP. The key is the `end` value. When I use `end` the entire line is highlighted. When I use `end - 1` only the text is highlighted. So you need to make sure the newline charater is included in the highlight. Maybe try using `end + 1`? If you still have problems then post your SSCCE, maybe this is a version/platform issue. – camickr Feb 14 '12 at 16:41
  • @camickr s/he use derivate of JTextArea by Fifesoft, – mKorbel Feb 14 '12 at 16:47
  • changing the end offset will just make the highlight go one line bellow I would guess. Ill check it tho. – Giannis Feb 14 '12 at 18:18
  • Tried the `end` idea with the default Swing JTextArea on JDK6_31 on Vista, and it never highlights the whole line: when I highlight up to the `\n` character, when the highlight includes the `\n` character and some character on the next line, when the `\n` is exactly the last character included in the range, when the highlight range is only the `\n` character (in this case no visual difference is observed). In all those cases the area to the right of the last character on the line remains white. – Evgeni Sergeev May 10 '16 at 01:27

2 Answers2

4

I'd suggest to use JTextPane / JEditorPane, these JTextComponents can be decorated and supporting styled Text, to the JTextPane / JEditorPane you can add any JComponent e.g. Icon... ), example for HighlightPainter

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • I am using RSyntaxTextArea since I want to write java code so changing component type is not an option. :/ http://javadoc.fifesoft.com/rsyntaxtextarea/ – Giannis Feb 14 '12 at 15:13
0

The idea from @camickr's LinePainter.java applies here: implement Highlighter.HighlightPainter, getting its paint(..) method to go outside of the bounds that it is given, painting a rectangle of the same height and full width.

Evgeni Sergeev
  • 22,495
  • 17
  • 107
  • 124