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

I implemented a Java Swing component that implements Printable. If I add a component to a JFrame and do it this.pack();on a JFrame, it will print fine. But if I do not add the component to the JFrame, only a blank page will be printed.

This code gives an excellent listing:

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 a big difference. How can I do pack()on my printable component so that it prints fine without adding it to the JFrame? The panel uses several LayoutManagers.

I tried with p.validate();and p.revalidate();, but it does not work. Any suggestions? Or do I need to add it to a hidden JFrame before printing the component?

: p.doLayout();, , . doLayout():

. , .

p.validate(); .

+3

Source: https://habr.com/ru/post/1746979/


All Articles