Milton90 Milton90 - 9 months ago 54
Java Question

Do a print screen of my java application

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

saveScreen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {


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()
            .createCompatibleImage(comp.getWidth(), comp.getHeight());
    Graphics graphics = image.createGraphics();
    // Print to BufferedImage
    // Output the `BufferedImage` via `ImageIO`
    try {
        ImageIO.write(image, "png", new File("Image.png"));
    } catch (IOException e) {

You need to at least

import java.awt.Component;
import java.awt.Graphics;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
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;

        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;

        protected void done() {
            if (success) {
                // notify user it succeed
            } else {
                // notify user it failed

And one more thing to import:

import javax.swing.SwingWorker;