How to print a page when a JButton is pressed in java swing using PrinterJob?
- by Prayag Upd
I tried the following code AWT but at runtime shows multiple print dialogs repeatedly....
package printerjob;
import java.awt.BasicStroke;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.WindowAdapter;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
/**
*
* @author pragX
*/
public class FramePrinterJob extends Frame implements Printable{
public void start(){
add(button);
}
@Override
public void paint(Graphics graphics){
PrinterJob printerJob=PrinterJob.getPrinterJob();
printerJob.setPrintable(this);
if(printerJob.printDialog()){
try{
printerJob.print();
}catch(PrinterException printerException){
//printerException.printStackTrace();
System.out.println("Error Printing." + printerException);
}
}
}
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
//throw new UnsupportedOperationException("Not supported yet.");
if(pageIndex>=1){
return Printable.NO_SUCH_PAGE;
}
graphics.translate((int) pageFormat.getImageableX(), (int)pageFormat.getImageableY());
Graphics2D graphics2D=(Graphics2D)graphics;
graphics2D.setStroke(new BasicStroke(4f));
graphics2D.drawLine(20, 20, 20, 120);
graphics2D.drawLine(40, 20, 40, 120);
graphics2D.drawLine(20, 70, 40, 70);
graphics2D.drawLine(60, 70, 60, 120);
graphics2D.drawLine(60, 40, 60, 45);
return Printable.PAGE_EXISTS;
}
public static void main(String args[]){
Frame frame=new FramePrinterJob();
frame.addWindowListener(new WindowAdapter() { public void windowClosing(){System.exit(0);}});
frame.setSize(300,400);
frame.setVisible(true);
}
}