The problem with ScreenShot is the native app exception. from the screen

I have a small problem that I really don't know how to solve, basically I want to take a screenshot (using the Robot class) on my desktop, excluding the actual GUI components of the program. Originally I thought this could be done by temporarily hiding the components, but every time a new screenshot is taken, the components are included in the image.

This is the block included in the actionPerformed method for the button that captures the screenshot:

if (command.equals("zoom")) {
    setComponentVisability(false);//try to hide the components from the robot
    zt.screenShoot();//take the screenshot
    setComponentVisability(true);//show the components


"zt.screenShoot" takes a screenshot and returns it to a new JFrame (for debugging), in my main frame I am using

com.sun.awt.AWTUtilities.setWindowOpaque(systemWindow, false);


to make the background transparent; not sure if it has anything to do with this issue.

any help would be great, thanks


source to share

1 answer

Use a short delay between hiding the component and taking a screenshot.


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

class TestScreenshot {

    static JLabel screenshot;

    public static void main(String[] args) throws Exception {
        final Robot robot = new Robot();
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                final JFrame f = new JFrame("Screenshot");

                JPanel gui = new JPanel(new BorderLayout(3,3));

                gui.setBorder(new EmptyBorder(5,5,5,5));



                screenshot = new JLabel();
                JScrollPane scroll = new JScrollPane(screenshot);
                scroll.setPreferredSize(new Dimension(800,600));
                gui.add(scroll, BorderLayout.CENTER);

                final ActionListener al = new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        Rectangle screenSize = new Rectangle(
                        Image image = robot.createScreenCapture(screenSize);

                JButton grabScreen = new JButton("Grab Screen");
                grabScreen.addActionListener( new ActionListener(){
                    public void actionPerformed(ActionEvent ae) {
                        Timer timer = new Timer(400, al);
                } );
                gui.add(grabScreen, BorderLayout.SOUTH);


    public static void setImage(Image image) {
        screenshot.setIcon(new ImageIcon(image));




All Articles