Tuesday, June 17, 2008

Using row highlighters in SwingX 0.9.3

I was excited to read about row highlighting in the JXTable SwingX component, and found a number of tutorials showing how to implement this. But, all of them show how to do it the same way, and none of them work any longer (at least as of v 0.9.2+). Here's the example code from the SwingLabs tutorial:

jxTable.setHighlighters(new HighlighterPipeline(
new Highlighter[]{ AlternateRowHighlighter.classicLinePrinter }));
There is no more "HighlighterPipeline", nor is there "AlternateRowHighlighter". I couldn't find any other up-to-date tutorials on the subject, so I did a little digging in the SwingX JavaDocs, and was able to put together the following code that accomplishes the same thing.
import java.awt.Color;
import org.jdesktop.swingx.decorator.*;
...
ColorHighlighter highlighter = new ColorHighlighter();
highlighter.setHighlightPredicate(HighlightPredicate.ODD);
highlighter.setBackground(Color.getHSBColor(0.62f, 0.01f, 0.92f)); //very light blue

DetailsTable.setHighlighters(highlighter);
Not much to explain here, just a different way of doing it. In addition to a number of other features, HighlightPredicate also supports "ROLLOVER_ROW", which works as you'd guess. "ROLLOVER_ROW" has also made the following unnecessary:
jxTable.setRolloverEnabled(true);
Code changes are obviously one of the problems with using pre-release code, though I've had great luck with SwingX components so far concerning stability. It's been worth the risk for me so far, though I'm not relying on the extra functions that SwingX provides for anything "mission critical" - just for row sorting, filtering, coloring, packing, etc.. JXTable inherits from the standard JTable, so if I decide to remove SwingX, there should be minimal pain involved (I hope).

1 comment:

Ash said...

Hey... I had a similar issue with this, but never investigated and stuck to pre-0.9.3 for business reasons; these changed :)

Very easy to achieve in 0.9.7:

table.addHighlighter(HighlighterFactory.createAlternateStriping());

Easily found in the JavaDoc too...