views:

343

answers:

2

I have a part of my app that takes a screenshot of a certain window but before I do so I want to bring the window to the front. This works fine on my Mac machine but when I tested it on in Windows XP on paralells the screenshot always has a greyed out area where the overlapping window was. It seems the screenshot is always taken while the window I want on top is being transfered to the top. Ive tried using both:

     frame.setVisible(true);
            and
     frame.setAlwaysOnTop(true);

Does anyone have a reasonable solution for this issue?

+1  A: 
  • You could add a delay the the thread that takes the screenshot.

  • You could fire the screenshot from the frame when the it has gained focus:

    class ScreenshotShooter implements FocusListener  {
        public void focusGained( FocusEvent e ) {
            // smile..... 
            // you may add a sec of delay here just be be sure.
        }
        public void focusLost( FocusEvent e ) {}
     }
    
    
     FocusListener focusListener = new ScreenshotShooter();
     frame.addFocusListener( focusListener );
     frame.setVisible( true ); // should autofire
     frame.remoe( focusListener);
    
  • You can do both.

OscarRyz
I tired that but the delay seemed to prolong the time it took for the refresh to occur. I was thinking I could maybe start a new thread the slept for a certain period of time, and lock that against the screenshot thread, but this all seems very sloppy and would not guarantee success on machines of differing speed.
Mike2012
Oh definitely that should be in another thread or at least using SwingUtilities.invokeLater() .... Otherwise you stop for a second, take the screenthot and theeen make it visible.
OscarRyz
That sounds like a reasonable solution, I'll try that. Thanks.
Mike2012
+1  A: 

If you are trying to take a screenshot of a window w painted by Java, you can just ask it to paint itself on a

BufferedImage bi = new BufferedImage(
    w.width, w.height, BufferedImage.TYPE_INT_RGB); 
Graphics g = bi.getGraphics();

by calling the windows' paint(g) method. You can then save the BufferedImage to a file. If you are grabbing an external window, then I believe Oscar Reyes has given you all the answers.

tucuxi
Awesome this worked perfectly and seems very clean. Thank you very much!
Mike2012
Awwn :( I thought you have covered that part already!!.. :)
OscarRyz