Sunday, 19 June 2016

Printing Checkboxes in Tables - Grossly Inefficient

Printing in Java has always seemed like a bit of a black art to me. With anything complicated, you need to manually determine where each bit of text should be placed on the page, how much space it takes up, and where/how to manage page breaks.

So I was thrilled when I found Java's JTable.print(..) method (http://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html#print%28%29) I thought it would make printing much easier. This method is really a great tool.

Then I decided to print a list of a few items. Take my JTable, print it, it renders just like it does on the screen and no need to do extra work. Piece of cake!

Or so I thought.

Expand that table to a list of a few hundred, or a few thousand items. Suddenly you're waiting half an hour to print a single page. What went wrong? I use a PDF printer for debugging because there's no sense killing trees, and the files were in the tens to hundreds of megabytes range....for text?

To be fair, and this may make a difference (I didn't check), I'm using the Nimbus look and feel. A little bit of debugging, commenting out the checkboxes from the table, and the printout was now the in the hundreds of kilobytes range, which was what I expected, and I was able to work around the problem.

Since I needed the printout to look exactly like the screen, I "solved" the problem by editing my custom renderer to return a checkbox if displaying for the screen, and a label that looks exactly like the checkbox if the table.isPaintingForPrint() method returned true.

if( table.isPaintingForPrint() )
{
    return printLabel;
} else
{
    return guiBox;
}

No comments:

Post a Comment