java - 打印我的 Java 应用程序的屏幕

标签 java jbutton printscreen

如何制作我的 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/

相关文章:

java - 格式化日期时间时如何应用时区?

java - 如何将 Jbutton 放置在所需位置并更改它们之间的颜色?

C++ RegisterHotKey 不覆盖现有功能

python - 用python模拟打印屏幕按键

java打印屏幕两个显示器

java - ListView 不显示在 Fragment 中 (Android)

java - 微调器中的 SimpleAdapter、文本和图像

java - 我将如何为这样的算法建立递归关系?

java - 需要 ActionListener 代码解释

java - 卡和 JButton