Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do a print screen of my java application

How can I make a print screen of my java application?

   saveScreen.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            ...
        }
    });
like image 475
Milton90 Avatar asked Dec 27 '22 01:12

Milton90


2 Answers

I'll give another method, it will print out the Component you passed in:

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();
    }
}

You need to at least

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;

To prevent blocking the EDT, ImageIO.write shouldn't be invoked on EDT, so replace the try-catch block with the following:

    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();

And one more thing to import:

import javax.swing.SwingWorker;
like image 175
johnchen902 Avatar answered Jan 08 '23 22:01

johnchen902


Here's an example of how you can make a capture of the screen:

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

Then, simply pass the BufferedImage to a stream that writes its content to a file.

like image 34
Konstantin Yovkov Avatar answered Jan 08 '23 20:01

Konstantin Yovkov