Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing headers and footers in color?

I am trying to create colored headers and footers when printing a JTable. Specifically, I am looking at getPrintable() in javax.swing.JTable, but MessageFormat does not give me the option to specify the color of the header or footer.

How can I do it?

clarification I am interested in setting the header/footers while printing. For example, notepad appends the filename as a header to what you print.

update Seems like there is no standard way of doing this, can someone give me some workarounds? The only answer posted so far has nothing to do with printing(as in send to a printer, not displaying to screen) header/footers.

Copied from my comment: I am interested in the printing header/footer. For example, when you are printing a document from notepad, it appends the filename as a header (or perhaps its the footer, I do not remember exactly)

like image 503
z - Avatar asked Dec 01 '25 05:12

z -


1 Answers

One solution I can think of is to use your own printable:

public class CustomTablePrintable implements Printable {

    Printable tablePrintable;

    public void setTablePrintable(Printable printable) {
        tablePrintable = printable;        
    }

    public int print(Graphics graphics, PageFormat pageFormat, 
            int pageIndex) throws PrinterException {
        if (pageIndex > 0) {
            return NO_SUCH_PAGE;
        }

        tablePrintable.print(graphics, pageFormat, pageIndex);

        Graphics2D g2d = (Graphics2D)graphics;
        g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

        // Draw header/footer here
        graphics.drawString(header, posx, posy);

        return PAGE_EXISTS;        
    }
}

When you call getPrintable from your JTable, inject it to a new instance to the custom printable and then use this with the PrinterJob.

You can now draw the header and footer as you wish, but you also lose some stuff:

  • You can't use MessageFormat to format the messages. I believe that you could easily add this functionality to your printable.
  • Header and footer aren't automatically positioned. You could have rough estimates for these though.

EDIT: I've looked at the Java Sources and there is the private class TablePrintable that does all the job. You can peak at the source code to see how the header and footer are printed. Then you can move this functionality to your Printable class.

like image 200
kgiannakakis Avatar answered Dec 03 '25 22:12

kgiannakakis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!