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?

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127

2 Answers2

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

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • 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. – Matthew Murdoch Dec 10 '08 at 09:41
  • Ok. I will check that later this day or tomorrow – VonC Dec 10 '08 at 10:14
  • I've found a solution for this (see my answer). Thanks. – Matthew Murdoch Dec 11 '08 at 15:52
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));
Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
  • Good catch! +1. I have updated my answer, and my own post on DZone Snippets, to include your line of code. – VonC Dec 11 '08 at 16:00
  • It does have the disadvantage however that it makes operations requiring text selection (cut, copy etc.) very difficult to use! – Matthew Murdoch Dec 11 '08 at 21:03