Java Tips Weblog

  • Blog Stats

    • 2,571,297 hits
  • Categories

  • Archives

Rectangle Painter

Posted by Rob Camick on October 28, 2008

All text components allow you to highlight certain portions of text. This is done by adding a highlight to the Highlighter. The highlight will then use a HighlightPainter to paint the highlight. The default painter  simply paints a coloured background. Effective but rather plain. Now is your chance to create a custom painter and jazz up the highlighting.

Lets start with a RectanglePainter. This was really easy because once you identify the actual code in the DefaultHighlighter.DefaultHighlightPainter class that does the painting, it is only a one line change. However, I refactored the code a bit to isolate this painting code from the code that determines the area to be painted. This will allow for easier customizations that you may want to do in the future.

The following code was used to creating the highlightings shown in the image:

RectanglePainter red = new RectanglePainter( Color.RED );
RectanglePainter cyan = new RectanglePainter( Color.CYAN );
textArea.getHighlighter().addHighlight(5, 9, red);
textArea.getHighlighter().addHighlight(61, 69, cyan);
textArea.getHighlighter().addHighlight(106, 110, red);

Squiggle Painter

The SquigglePainter is an example of a painter that will underline the text with a squiggly line. You may want to play with the squiggle size to see what you prefer. I would recommend 2 or 3 otherwise the squiggle gets too big.

Squiggle-Painter

There is not much more to say about this class. Once you have a Graphics object and a drawing area, the highlighting possibilities are only limited by your imagination. Hopefully these two examples will get you started.

Get The Code

RectanglePainter.java
SquigglePainter.java

Related Reading

2D Painting

2 Responses to “Rectangle Painter”

  1. Antonio said

    I don´t know how to implement in my code, i have a JTextArea, i copied your code but it doesn’t work for me. Could you help me? Please.

Leave a comment