How to print a page when a JButton is pressed in java swing using PrinterJob?
Posted
by
Prayag Upd
on Stack Overflow
See other posts from Stack Overflow
or by Prayag Upd
Published on 2010-12-25T04:39:41Z
Indexed on
2010/12/25
4:54 UTC
Read the original article
Hit count: 270
java
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);
}
}
© Stack Overflow or respective owner