Mil*_*n90 4 java printscreen jbutton
如何制作我的java应用程序的打印屏幕?
saveScreen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
...
}
});
Run Code Online (Sandbox Code Playgroud)
我会给出另一种方法,它会打印出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();
}
}
Run Code Online (Sandbox Code Playgroud)
你需要至少
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;
Run Code Online (Sandbox Code Playgroud)
为了防止阻止EDT,ImageIO.write不应该在EDT上调用,所以用以下代码替换try- catchblock:
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();
Run Code Online (Sandbox Code Playgroud)
还有一件事要导入:
import javax.swing.SwingWorker;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7084 次 |
| 最近记录: |