Java(Netbeans)Print正在生成一个空白页面

时间:2017-11-26 18:05:57

标签: java swing printing

非常感谢任何帮助。 我已经使用此代码尝试打印j帧的内容,但它只打印一个空白页。我试过添加各种进口等,但我似乎无法让它发挥作用。 (我的包围可能已关闭,因为我已快速删除任何不相关的代码!) 这是我写的代码:

package MenuPackage;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.awt.event.ActionListener;
import java.awt.print.*;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class SimplePrint extends javax.swing.JFrame implements Printable {
JFrame frameToPrint;

static JFrame SP = new SimplePrint();

public SimplePrint() {
    initComponents();
}

public SimplePrint(JFrame f){
    frameToPrint = f;

}


private void initComponents() {


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         


    PrinterJob PJ   =   PrinterJob.getPrinterJob();
    //PageFormat PF   =   PJ.pageDialog(PJ.defaultPage());
    PJ.setPrintable((Printable) this);
    boolean doPrint = PJ.printDialog();

    //JOptionPane.showMessageDialog(null, doPrint);
    if(doPrint){
        try {
            PJ.print();
        } catch (PrinterException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
       }
    }

}                                        


public int print(Graphics g, PageFormat pageFormat, int pageIndex) 
    throws PrinterException {
    if (pageIndex > 0) {
      return(NO_SUCH_PAGE);
    } else {
      Graphics2D g2d = (Graphics2D)g;
      g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
      // Turn off double buffering
      //componentToBePrinted.paint(g2d);
      //frameToPrint.print(g);
      SP.print(g);
      // Turn double buffering back on
      return(PAGE_EXISTS);
    }
  }
{




    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            SP.setVisible(true);
        }
    });
}


}

0 个答案:

没有答案