做我的java应用程序的打印屏幕

时间:2013-06-29 11:49:20

标签: java jbutton printscreen

如何制作我的java应用程序的打印屏幕?

   saveScreen.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            ...
        }
    });

2 个答案:

答案 0 :(得分:6)

我会给出另一种方法,它会打印出你传入的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块:

    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;

答案 1 :(得分:4)

以下是如何捕获屏幕的示例:

Robot robot = new Robot();
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = robot.createScreenCapture(screenRect);

然后,只需将BufferedImage传递给将其内容写入文件的流。