How to Print JFrame in Java | Java Support | Project Solutions | Tech Blicks

In this Blog post, you can learn the code of Printing JFrames in JAVA. By Using this code you can Print your Jframe formats.

  • Make Your JFrame Format.
  • Drag a Button in Jframe to use as Print Command Button.

Tech Blicks

  • Write the Following code in the Jbutton Action Performed

jButton1.setVisible(false);
PrinterJob pjob = PrinterJob.getPrinterJob();
PageFormat preformat = pjob.defaultPage();
preformat.setOrientation(PageFormat.PORTRAIT);
PageFormat postformat = pjob.pageDialog(preformat);
//If user does not hit cancel then print.
pjob.setPrintable( this);
if (pjob.printDialog()) {
try {
pjob.print();
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
else{
System.out.print(“fjk”);
}
this.dispose();

  • Write the following Code in Class of Jframe

public int print(Graphics g, PageFormat format, int page_index)
throws PrinterException {
if (page_index > 0) {
return Printable.NO_SUCH_PAGE;
}
// get the bounds of the component
Dimension dim = this.getSize();
double cHeight = dim.getHeight();
double cWidth = dim.getWidth();
// get the bounds of the printable area
double pHeight = format.getImageableHeight();
double pWidth = format.getImageableWidth();
double pXStart = format.getImageableX();
double pYStart = format.getImageableY();
double xRatio = pWidth / cWidth;
double yRatio = pHeight / cHeight;
Graphics2D g2 = (Graphics2D) g;
g2.translate(pXStart, pYStart);
g2.scale(xRatio, yRatio);
this.paint(g2);
/* Graphics2D g2d = (Graphics2D)g;
g2d.translate(format.getImageableX(), format.getImageableY());
/* Now print the window and its visible contents */
// printAll(g);*/
/* tell the caller that this page is part of the printed document */
return PAGE_EXISTS;
//return Printable.PAGE_EXISTS;
}

  • Implement your Class to “Printable”.

Leave your Precious Comments Below. If you have any problem in code or anything else comment below or you can contact us here or mail us here.

Leave a Comment

Your email address will not be published. Required fields are marked *