How can I "pack()" a printable Java Swing component?

Posted by Jonas on Stack Overflow See other posts from Stack Overflow or by Jonas
Published on 2010-05-25T09:52:37Z Indexed on 2010/05/25 10:01 UTC
Read the original article Hit count: 249

Filed under:
|
|
|

I have implemented a Java Swing component that implements Printable. If I add the component to a JFrame, and do this.pack(); on the JFrame, it prints perfect. But if I don't add the component to a JFrame, just a blank page is printed.

This code gives a great printout:

final PrintablePanel p = new PrintablePanel(pageFormat);
new JFrame() {{ getContentPane().add(p); this.pack(); }};
job.setPrintable(p, pageFormat);
try {
    job.print();
} catch (PrinterException ex) {
    System.out.println("Fail");
}

But this code gives a blank page:

final PrintablePanel p = new PrintablePanel(pageFormat);
// new JFrame() {{ getContentPane().add(p); this.pack(); }};
job.setPrintable(p, pageFormat);
try {
    job.print();
} catch (PrinterException ex) {
    System.out.println("Fail");
}

I think that this.pack(); is the big difference. How can I do pack() on my printable component so it prints fine, without adding it to a JFrame? The panel is using several LayoutManagers.

I have tried with p.validate(); and p.revalidate(); but it's not working. Any suggestions? Or do I have to add it to a hidden JFrame before I print the component?

© Stack Overflow or respective owner

Related posts about java

Related posts about swing