gpt4 book ai didi

java - Printable 打印整个框架而不是内容

转载 作者:行者123 更新时间:2023-12-01 23:37:43 25 4
gpt4 key购买 nike

我想打印 BufferedImage,我不知道如何打印,所以我尝试打印所有内容。
代码似乎工作正常,除了它还打印框架的边框和打印按钮,而不仅仅是预期的内容。
而且由于某种原因,质量变得很糟糕。

这是我为其编写的代码:

package frik.main;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
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.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;

import java.awt.event.*;

import javax.swing.*;
import frik.data.Config;
import frik.utils.ImgUtil;

public class Previewer implements Config, Printable, ActionListener{

private JFrame Frame;
private JPanel ImagePanel;
private JLabel PicLabel;
private JButton PrintButton;
private static BufferedImage before;
private static boolean Scaled;

public Previewer(BufferedImage Image, boolean scaled){
this.before = Image;
this.Scaled = scaled;
loop();

}

public int print(Graphics g, PageFormat pf, int page) throws PrinterException{
if (page > 0) {
return Printable.NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pf.getImageableX(), pf.getImageableY());

Frame.printAll(g);

return Printable.PAGE_EXISTS;
}

public void actionPerformed(ActionEvent e){
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(this);
boolean ok = job.printDialog();
if (ok) {
try {
job.print();
} catch (PrinterException ex) {
JOptionPane.showMessageDialog(null, "The Printjob did not successfully complete.", "Print Failure.", JOptionPane.WARNING_MESSAGE);
}
}
}

public void loop(){
UIManager.put("swing.boldMetal", Boolean.FALSE);
Frame = new JFrame("Mold Preview");
ImagePanel = new JPanel();
PrintButton = new JButton("Print Mold");

Frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});

if(Scaled){
PicLabel = new JLabel(new ImageIcon(ImgUtil.scaleImage(PAPER_WIDTH / 3, PAPER_HEIGHT / 3, before)));
}else if (!Scaled){
PicLabel = new JLabel(new ImageIcon(before));
}

ImagePanel.setBackground(Color.orange);
ImagePanel.add(PicLabel);
Frame.add("Center", ImagePanel);

PrintButton.addActionListener(this);
Frame.add("North", PrintButton);

Frame.pack();
Frame.setVisible(true);
Frame.setResizable(false);

}

public static void main(String args[]){
new Previewer(before, Scaled);
//////////////////////////////
}
}

因此,如果有人可以帮助我仅打印 BufferedImage,或者仅打印包含 BufferedImage 的 ImageIcon,那就太好了。

最佳答案

首先,如果您只关心打印图像,为什么要调用 Frame.printAll(g) 呢?不要这样做,只需尝试绘制图像:

g.drawImage(Image, x, y, null);

关于java - Printable 打印整个框架而不是内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18429380/

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