[ACCEPTED]-How can I print a single JPanel's contents?-printing
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
}
}
0
A simple way to do it would be implementing 10 the Printable
interface (in java.awt.print
) and adding the specified 9 print
method (it works similar to paint
—in here, you 8 could specify what components you would 7 want to draw onto the printed page). And 6 when you want to actually print the contents 5 of the panel, obtain a PrinterJob
instance and call 4 its setPrintable
method, passing the object that implemented 3 Printable
.
That's just a quick overview, though. I'd 2 recommend taking a look at Sun's tutorial on printing for further 1 information.
just edit and put the name of your frame, panel(jPanel1) and 4 button(print). 'this' refers to the JFrame 3 class(i.e my class extends javax.swing.JFrame 2 ) just put your frame's reference instead 1 of '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();
}
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.