Reputation: 11
Hello everyone, Now a days i am facing a serious problem. I have made a java program and one of the JFrame of this program needs to be printed. But i can't do that. I have searched on the web but the code i have found only prints the first element means just 1 element may be JLabel or JTextBox. But i need to print the whole page with all data.
Can anyone please help me?
Thanks
Upvotes: 1
Views: 259
Reputation: 316
Attach this code to your class. Hope this will help you
First of all implement the Printable interface to your Java class
class ClassName extends JFrame implements Printable
{
//your code goes here
}
After implementing Printable interface override the method print()
public int print(Graphics g, PageFormat pf, int page) throws PrinterException {
if (page > 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D) g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
//Give the component to be printed here...
System.out.println("Successfully printed");
return PAGE_EXISTS;
}
Now decide what you want to print. Write your code in such a way that all the components must be on one parent JPanel(parentPanel). Now in the above code next to the comment give parentPanel.print(g)
This will print all the components on that parentPanel.
Now we told out Java program what to be printed but to complete this printing job we have to create PrinterJob
PrinterJob job = PrinterJob.getPrinterJob(); job.setPrintable(this); boolean ok = job.printDialog(); if (ok) { try { job.print(); } catch (PrinterException ex) { System.out.println(ex); } }
Place this code in the ActionListener of your print button.
Upvotes: 0