How can I "pack()" a printable Java Swing component?
- by Jonas
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?