MattG
MattG

Reputation: 1426

Overlapped highligted text color in JTextPane

I have created a Swing interface that uses a JTextPane. The JTextPane is highlighted with custom colors using:

textPane.getHighlighter().addHighlight(startPos, endPos, highlightPainter); 

The user is also able to highlight text with the cursor in the ordinary fashion.

My problem is that I can't figure out a way for text that is highlighted by both the highlighter object and cursor selection to be colored a third, different color. The highlighter object's highlighting always takes precedence.

I tried using a CaretListener object, but it only fires events when the user releases the mouse after highlighting manually. I need the overlap to render while the user is adjusting the highlighted region with the cursor.

I would even be happy with the cursor highlighting taking precedence over the highlighter object's highlightings instead, but the unique overlap color is a preferable feature.

The following question is similar to mine:

How to use LayeredHighlighter - One highlight on top of another

but the only answer just links to methods that overlay a GlassPane. I would much prefer a JTextPane or document-level solution, however, because the value of the selected text is important via

textPane.getSelectionStart();

and

textPane.getSelectionEnd();

Upvotes: 2

Views: 319

Answers (2)

MattG
MattG

Reputation: 1426

I constructed the non-selection, custom highlighting colors with an alpha value for transparency (the default is complete opaqueness):

Color myColor = new Color( rValFloat, gValFloat, bValFloat, alpha);

This doesn't give me complete control of the overlapped region's color since the highlighting is a mix of the cursor highlighting and my color above, but I can also change the cursor's selection color with:

textPane.setSelectionColor(mySelectionColor);

which is enough control for my purposes.

Upvotes: 0

camickr
camickr

Reputation: 324108

I would even be happy with the cursor highlighting taking precedence over the highlighter object's highlightings instead

JTextPane textPane = new JTextPane(...);
DefaultHighlighter highlighter =  (DefaultHighlighter)textPane.getHighlighter();
highlighter.setDrawsLayeredHighlights(false);

Upvotes: 8

Related Questions