Java 如何打印单个 JPanel 的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/750310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I print a single JPanel's contents?
提问by Talha Bin Shakir
I have a JPanel
with two labels with pictures. I need to print these content of the JPanel
. Please help me out. How can I print only this JPanel
's contents, as I also have different components on my JFrame
but I just need to print thisJPanel
.
我有一个JPanel
带有图片的两个标签。我需要打印JPanel
. 请帮帮我。我怎样才能只打印这个JPanel
的内容,因为我也有不同的组件,JFrame
但我只需要打印这个JPanel
.
Thanks.
谢谢。
采纳答案by Talha Bin Shakir
Here is an example to print any Swing component.
这是打印任何 Swing 组件的示例。
public void printComponenet(Component component){
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setJobName(" Print Component ");
pj.setPrintable (new Printable() {
public int print(Graphics pg, PageFormat pf, int pageNum){
if (pageNum > 0){
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) pg;
g2.translate(pf.getImageableX(), pf.getImageableY());
component.paint(g2);
return Printable.PAGE_EXISTS;
}
});
if (pj.printDialog() == false)
return;
try {
pj.print();
} catch (PrinterException ex) {
// handle exception
}
}
回答by hbw
A simple way to do it would be implementing the Printable
interface (in java.awt.print
) and adding the specified print
method (it works similar to paint
—in here, you could specify what components you would want to draw onto the printed page). And when you want to actually print the contents of the panel, obtain a PrinterJob
instance and call its setPrintable
method, passing the object that implemented Printable
.
一个简单的方法是实现Printable
接口 (in java.awt.print
) 并添加指定的print
方法(它的工作原理类似于paint
- 在此处,您可以指定要在打印页面上绘制的组件)。当你想真正打印面板的内容时,获取一个PrinterJob
实例并调用它的setPrintable
方法,传递实现Printable
.
That's just a quick overview, though. I'd recommend taking a look at Sun's tutorial on printingfor further information.
不过,这只是一个快速概述。我建议您查看Sun 的打印教程以获取更多信息。
回答by YasirAzgar
just edit and put the name of your frame, panel(jPanel1) and button(print). 'this' refers to the JFrame class(i.e my class extends javax.swing.JFrame ) just put your frame's reference instead of 'this'.
只需编辑并输入框架的名称,面板(jPanel1)和按钮(打印)。'this' 指的是 JFrame 类(即我的类扩展 javax.swing.JFrame )只是把你的框架的引用而不是 'this'。
private void PritnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Toolkit tkp = jPanel1.getToolkit();
PrintJob pjp = tkp.getPrintJob(this, null, null);
Graphics g = pjp.getGraphics();
jPanel1.print(g);
g.dispose();
pjp.end();
}