How can I print a single JPanel's contents?
Solution 1
Here is an example to print any Swing component.
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
}
}
Solution 2
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
.
That's just a quick overview, though. I'd recommend taking a look at Sun's tutorial on printing for further information.
Diego Fosso
Updated on July 09, 2022Comments
-
Diego Fosso almost 2 years
I have a
JPanel
with two labels with pictures. I need to print these content of theJPanel
. Please help me out. How can I print only thisJPanel
's contents, as I also have different components on myJFrame
but I just need to print thisJPanel
.Thanks.
-
Saher Ahwal about 13 yearshow can you scale the component accordingly in the page so that it fits?
-
Sam Jarman almost 11 years@Saher did you ever figure out how to do this? Thanks
-
ArchLinuxTux over 6 yearscould you please add more explanation (text)? Is one supposed to derive a JComponent and add this method or what shall one do with this? Thank you.
-
ArchLinuxTux over 6 yearslook at this for a multi page printer of
Component