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.