2011-03-15 100 views
1

如何打印JFrame的內容?在java中打印jframe

+5

打印到屏幕,標準輸出或打印機? – 2011-03-15 16:06:52

+1

Oohh JFrame到AsciiArt轉換器,這將很有趣。 – 2011-03-15 16:08:11

+1

此鏈接提供了您正在尋找的其他有用的提示http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-Printing.html – 2011-03-15 16:44:40

回答

2
 PrinterJob job = PrinterJob.getPrinterJob(); 
    job.setPrintable(this); 
    boolean ok = job.printDialog(); 
     if (ok) 
     { 
      try 
      { 
       job.print(); 
      } 
      catch (PrinterException ex) 
      { 
      /* The job did not successfully complete */ 
      } 
     } 

     public int print(Graphics g, PageFormat pf, int page) throws 
                PrinterException { 

    if (page > 0) { /* We have only one page, and 'page' is zero-based */ 
     return NO_SUCH_PAGE; 
    } 

    /* User (0,0) is typically outside the imageable area, so we must 
    * translate by the X and Y values in the PageFormat to avoid clipping 
    */ 
    Graphics2D g2d = (Graphics2D)g; 
    g2d.translate(pf.getImageableX(), pf.getImageableY()); 

    /* Now print the window and its visible contents */ 
    jFrame.paint(g2d); 
    jFrame.repaint(); 
    /* tell the caller that this page is part of the printed document */ 
    return PAGE_EXISTS; 
}