开发者

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

开发者 https://www.devze.com 2023-01-01 10:31 出处:网络
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 JF

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 sh开发者_如何学JAVAould invoke the validate method instead.

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消