gpt4 book ai didi

java - 如何使用 PrinterJob 在 java swing 中按下 JButton 时打印页面?

转载 作者:行者123 更新时间:2023-11-30 09:51:46 25 4
gpt4 key购买 nike

我尝试了以下 AWT 代码,但在运行时重复显示多个打印对话框....

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);
}
}

最佳答案

您可能不想为此覆盖 Framepaint() 方法。相反,在打印按钮的 actionPerformed() 方法中调用打印对话框,如 example 所示来自 A Basic Printing Program .

关于java - 如何使用 PrinterJob 在 java swing 中按下 JButton 时打印页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4529316/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com