Java打印JFrame

Java打印JFrame,java,swing,printing,Java,Swing,Printing,我希望你能帮忙。我正在尝试用java打印JFrame。它不一定是整个JFrame,只是一个我将添加文本和图像的小区域。如果我能让JLabel打印出来,那应该是一个好的开始。我需要在用户在文本字段中执行操作(已执行操作)时打印它,而不是像在其他代码(PrintUIWindow)中那样在用户单击打印时打印它 我在网上找到了一些代码(PrintUIWindow),我想把它们放到我的代码中,但运气不好。代码是可以工作的,但我只是不知道应该把它放在jframe的什么地方 public int print(

我希望你能帮忙。我正在尝试用java打印JFrame。它不一定是整个JFrame,只是一个我将添加文本和图像的小区域。如果我能让JLabel打印出来,那应该是一个好的开始。我需要在用户在文本字段中执行操作(已执行操作)时打印它,而不是像在其他代码(PrintUIWindow)中那样在用户单击打印时打印它

我在网上找到了一些代码(PrintUIWindow),我想把它们放到我的代码中,但运气不好。代码是可以工作的,但我只是不知道应该把它放在jframe的什么地方

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 */
    frameToPrint.printAll(g);

    /* tell the caller that this page is part of the printed document */
    return PAGE_EXISTS;
}
然后,我会在执行的操作中添加以下内容

 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 */
         }
     }
附件是我的代码的基本部分。如果有人能帮我写代码,我将不胜感激

package javaapplication42;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
import javax.print.attribute.standard.PrinterResolution;
import javax.swing.JFrame;
import static jdk.nashorn.internal.objects.Global.print;
import static sun.misc.Version.print;
import static sun.misc.Version.print;


public class NewJFrame extends javax.swing.JFrame implements Printable, ActionListener {

/**
 * Creates new form NewJFrame
 */
public NewJFrame() {
    initComponents();


}

public int print(Graphics g, PageFormat format, int pagenum) {

   if (pagenum > 0){
       return Printable.NO_SUCH_PAGE;
   }

   g.translate((int)format.getImageableX(), (int)format.getImageableY());

   float pageWidth = (float)format.getImageableWidth();
   float pageHeight = (float)format.getImageableHeight();

   float imageHeight = (float)this.getHeight();
   float imageWidth = (float)this.getWidth();

   float scaleFactor = Math.min((float)pageWidth/(float)imageWidth, (float)pageHeight/(float)imageHeight);

   int scaledWidth = (int)(((float)imageWidth)*scaleFactor);

   int scaledHeight = (int)(((float)imageHeight)*scaleFactor);  

   BufferedImage canvas = new BufferedImage( this.getWidth(),  this.getHeight(), BufferedImage.TYPE_INT_RGB);
   Graphics2D gg = canvas.createGraphics();
   this.paint( gg );  
   Image img = canvas ;

   g.drawImage(img, 0, 0, scaledWidth, scaledHeight, null );

   return Printable.PAGE_EXISTS;

}


/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jTextField1 = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jTextField1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jTextField1ActionPerformed(evt);
        }
    });

    jLabel1.setText("TEXT TO PRINT");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel1))
            .addContainerGap(316, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(30, 30, 30)
            .addComponent(jLabel1)
            .addGap(18, 18, 18)
            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(218, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
     /* The job did not successfully complete 
    PrinterJob job = PrinterJob.getPrinterJob();
 job.setPrintable(this);
 boolean ok = job.printDialog();
 if (ok) {
     try {
          job.print();
     } catch (PrinterException ex) {

     }
 }
 */

     PrinterJob job = PrinterJob.getPrinterJob();

    PageFormat format = job.defaultPage();
    format.setOrientation(PageFormat.LANDSCAPE);

    job.setPrintable(this, format);

    try{
        if(job.printDialog()) job.print();
    }
    catch(Exception e){e.printStackTrace();}




}                                           

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

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

// Variables declaration - do not modify                     
private javax.swing.JLabel jLabel1;
private javax.swing.JTextField jTextField1;
// End of variables declaration                   

@Override
public void actionPerformed(ActionEvent ae) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}


}
PackageJavaApplication42;
导入java.awt.Graphics;
导入java.awt.Graphics2D;
导入java.awt.Image;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.awt.image.buffereImage;
导入java.awt.print.PageFormat;
导入java.awt.print.Printable;
导入java.awt.print.PrinterException;
导入java.awt.print.PrinterJob;
导入javax.print.attribute.HashPrintRequestAttributeSet;
导入javax.print.attribute.PrintRequestAttributeSet;
导入javax.print.attribute.standard.MediaSizeName;
导入javax.print.attribute.standard.PrinterResolution;
导入javax.swing.JFrame;
导入静态jdk.nashorn.internal.objects.Global.print;
导入静态sun.misc.Version.print;
导入静态sun.misc.Version.print;
公共类NewJFrame扩展了javax.swing.JFrame实现了可打印的ActionListener{
/**
*创建新表单NewJFrame
*/
公共NewJFrame(){
初始化组件();
}
公共整型打印(图形g、页面格式、整型页面编号){
如果(pagenum>0){
返回可打印的。无此页面;
}
g、 翻译((int)format.getImageableX(),(int)format.getImageableY());
float pageWidth=(float)格式。getImageableWidth();
float pageHeight=(float)格式。getImageableHeight();
float imageHeight=(float)this.getHeight();
float imageWidth=(float)this.getWidth();
float scaleFactor=Math.min((float)pageWidth/(float)imageWidth,(float)pageHeight/(float)imageHeight);
int scaledWidth=(int)((float)imageWidth)*scaleFactor);
int scaledHeight=(int)((float)imageHeight)*scaleFactor);
BuffereImage画布=新的BuffereImage(this.getWidth()、this.getHeight()、BuffereImage.TYPE_INT_RGB);
Graphics2D gg=canvas.createGraphics();
这个。油漆(gg);
图像img=画布;
g、 drawImage(img,0,0,scaledWidth,scaledHeight,null);
返回Printable.PAGE_存在;
}
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
//                           
私有组件(){
jTextField1=newjavax.swing.JTextField();
jLabel1=newjavax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTextField1.addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
JTextfield1执行的操作(evt);
}
});
jLabel1.setText(“要打印的文本”);
javax.swing.GroupLayout=newjavax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(布局);
layout.setHorizontalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.training)
.addComponent(jTextField1,javax.swing.GroupLayout.PREFERRED_SIZE,63,javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addContainerGap(316,短,最大值))
);
layout.setVerticalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30,30,30)
.addComponent(jLabel1)
.addGap(18,18,18)
.addComponent(jTextField1,javax.swing.GroupLayout.PREFERRED\u SIZE,javax.swing.GroupLayout.DEFAULT\u SIZE,javax.swing.GroupLayout.PREFERRED\u SIZE)
.addContainerGap(218,简称最大值))
);
包装();
}//                         
private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt){
//TODO在此处添加您的处理代码:
/*作业未成功完成
PrinterJob job=PrinterJob.getPrinterJob();
作业。可设置打印(此);
布尔ok=job.printDialog();
如果(确定){
试一试{
job.print();
}捕获(打印例外){
}
}
*/
PrinterJob job=PrinterJob.getPrinterJob();
PageFormat format=job.defaultPage();
format.setOrientation(PageFormat.LANDSCAPE);
作业.setPrintable(此格式);
试一试{
if(job.printDialog())job.print();
}
catch(异常e){e.printStackTrace();}
}                                           
/**
*@param指定命令行参数
*/
公共静态void main(字符串参数[]){
/*设置Nimbus的外观和感觉*/
//
/*如果Nimbus(在JavaSE6中引入)不可用,请使用默认的外观。
*详情请参阅http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
*/
试一试{
for(javax.swing.UIManager.LookAndFeelInfo:javax.swing.UIManager.getInstalledLookAndFeels()){
if(“Nimbus”.equals(info.getName())){
setLookAndFeel(info.getClassName());
打破
}
}
}捕获(ClassNotFoundException ex){
getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);
}捕获(实例化)