我已经实现了一个实现 Printable
的 Java Swing 组件。如果我将组件添加到 JFrame,并在 JFrame 上执行 this.pack();
,它会完美打印。但是,如果我不将组件添加到 JFrame,则只会打印空白页。
这段代码给出了很好的打印输出:
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");
}
但是这段代码给出了一个空白页:
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");
}
我认为 this.pack();
是最大的区别。如何在可打印组件上执行 pack()
以便打印良好,而不将其添加到 JFrame 中?该面板使用多个布局管理器。
我尝试过 p.validate();
和 p.revalidate();
但它不起作用。有什么建议吗?或者在打印组件之前我是否必须将其添加到隐藏的 JFrame 中?
更新:如果我执行p.doLayout();
,则会打印一些部分,但不会打印子组件。并来自 的文档doLayout()
:
使该容器布置其组件。大多数程序不应直接调用此方法,而应调用 validate 方法。
但是 p.validate();
对我来说不工作。
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.
发布评论
评论(1)
您可以使用
invalidate()
,这将导致validate()
调用validateTree()
;或者,使用直接使用validateTree()
。@TacB0sS 似乎提出了一个很好的观点:根本不调用
setVisible()
;此相关上一个问题是引用以供参考。You could use
invalidate()
, which will causevalidate()
to invokevalidateTree()
; alternatively, usevalidateTree()
directly.@TacB0sS seems to make a good point: simply don't invoke
setVisible()
; this related previous question is cited for reference.