How do I get a JEditorPane to highlight the full width of a line (not just the text)?
Asked Answered
P

2

4

I'm trying to get a JEditorPane to highlight the full width of a displayed line. All the examples I've tried only highlight the textual content. For example if I have content such as this:

 ---------------------------------
|Here is some text                |
|some more text                   |
 ---------------------------------

within a JEditorPane represented by the box above, then highlighting the first row highlights only the 'Here is some text' (represented between [ and ] below).

 ---------------------------------
[Here is some text]               |
|some more text                   |
 ---------------------------------

I would like it to highlight the full width of the JEditorPane like the following:

 ---------------------------------
[Here is some text                ]
|some more text                   |
 ---------------------------------

Is there a way to do this?

Pungy answered 9/12, 2008 at 17:3 Comment(0)
C
4

This seems not too complicated. I would make that a little code-challenge.

Just create your own custom Highlighter, extending DefaultHighlighter.

Override the paint() method, and simply leave unchanged the width of the rectangle paint: it will be the width of the panel.

You will find in DZone Snippets a complete example: copy it and run it. Tell me if this is what you are after. It includes the textPane.setSelectionColor(new Color(1.0f, 1.0f, 1.0f, 0.0f)); addition you mention in your answer.

alt text http://www.freeimagehosting.net/uploads/94a3a990e4.png

Calyces answered 9/12, 2008 at 21:23 Comment(3)
Thank you. This is very very nearly what I'm after. The only problem is that it interacts badly with selection highlighting (leaving blocks of apparently selected text hanging around after deselecting). For my purposes, if I was able to turn off selection entirely that would probably do the job.Pungy
Ok. I will check that later this day or tomorrowCalyces
I've found a solution for this (see my answer). Thanks.Pungy
P
1

To prevent selection highlighting from interfering with VonC's solution I added the following line to the TextHighlight constructor (essentially making the selection highlight invisible):

textPane.setSelectionColor(new Color(1.0f, 1.0f, 1.0f, 0.0f));
Pungy answered 11/12, 2008 at 15:52 Comment(2)
Good catch! +1. I have updated my answer, and my own post on DZone Snippets, to include your line of code.Calyces
It does have the disadvantage however that it makes operations requiring text selection (cut, copy etc.) very difficult to use!Pungy

© 2022 - 2024 — McMap. All rights reserved.