views:

61

answers:

2

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?

UPDATE: If I do p.doLayout(); some parts are printed, but not the subcomponents. And from the documentation of doLayout():

Causes this container to lay out its components. Most programs should not call this method directly, but should invoke the validate method instead.

But p.validate(); is not working for me.

A: 

did you try to repaint it?

Did you set the panel size??

TacB0sS
Yes, the Size and PreferredSize is set in the constructor of the JPanel. But it doesn't help :(
Jonas
what do you have on your panel?components/image
TacB0sS
besides what is that terrible with having a ghost frame for a sec?
TacB0sS
@TacB0sS: I have many components, mainly JComponents, JLabels and JTextFields.
Jonas
@TacB0sS: There is no `setBufferStrategy`-method in `JPanel`
Jonas
sorry my friend I'm dry... you still didn't answer me about comment 3:"besides what is that terrible with having a ghost frame for a the printing process?"
TacB0sS
+2  A: 

You could use invalidate(), which will cause validate() to invoke validateTree(); alternatively, use validateTree() directly.

@TacB0sS seems to make a good point: simply don't invoke setVisible(); this related previous question is cited for reference.

trashgod
Thanks! `validateTree()` worked perfectly!
Jonas