开发者

How to print a page when a JButton is pressed in java swing using PrinterJob?

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 ar开发者_运维问答gs[]) {
        Frame frame=new FramePrinterJob();
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(){
                System.exit(0);
            }
        });
        frame.setSize(300,400);
        frame.setVisible(true);
    }
}


You probably don't want to override the paint() method of Frame for this. Instead, invoke the print dialogs in your print button's actionPerformed() method, as seen in this example from A Basic Printing Program.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜