如何制作我的 java 应用程序的打印屏幕?
saveScreen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
...
}
});
最佳答案
我再给出一个方法,它会打印出你传入的Component
:
private static void print(Component comp) {
// Create a `BufferedImage` and create the its `Graphics`
BufferedImage image = GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration()
.createCompatibleImage(comp.getWidth(), comp.getHeight());
Graphics graphics = image.createGraphics();
// Print to BufferedImage
comp.paint(graphics);
graphics.dispose();
// Output the `BufferedImage` via `ImageIO`
try {
ImageIO.write(image, "png", new File("Image.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
你至少需要
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
为防止阻塞 EDT,不应在 EDT 上调用 ImageIO.write
,因此将 try
-catch
block 替换为以下:
new SwingWorker<Void, Void>() {
private boolean success;
@Override
protected Void doInBackground() throws Exception {
try {
// Output the `BufferedImage` via `ImageIO`
if (ImageIO.write(image, "png", new File("Image.png")))
success = true;
} catch (IOException e) {
}
return null;
}
@Override
protected void done() {
if (success) {
// notify user it succeed
System.out.println("Success");
} else {
// notify user it failed
System.out.println("Failed");
}
}
}.execute();
还有一件事要导入:
import javax.swing.SwingWorker;
关于java - 打印我的 Java 应用程序的屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17379855/