take screenshots

i continue to spit out small useful stuff that might interest someone. again, nothing fancy.

i’m getting lots of useful stuff in my Tools class now… might release a lib some day.


public static void takeScreenShot(String filename, Component con) {
            try {
                  Robot r = new Robot();
                  Rectangle rect = new Rectangle(con.getLocationOnScreen().x, con.getLocationOnScreen().y, con.getWidth(), con.getHeight());
                  //BufferedImage image = r.createScreenCapture(rect);
                  BufferedImage image = (BufferedImage) con.createImage(con.getWidth(), con.getHeight());
                  con.paint(image.getGraphics());
                  int i = 1;
                  File f = new File(filename + i + ".jpg");                  
                  while (f.exists()) {
                        i++;
                        f = new File(filename + i + ".jpg");
                  }
                  ImageIO.write(image, "jpg", f);
            }
            catch (AWTException e1) {}
            catch (IOException e2) {}
      }

EDIT: changed the naming a little

How would overlapping windows effect your code?

I haven’t done it but wouldn’t the following psudo code be less error prone?

Image image = createImage(con.getWidth(), con.getHeight());
con.pain(image.getGraphics());
// Then your file output code to create the jpg.

it grabs whatever is visible in the speciefied area

in fullscreen this isn’t a problem, but in windowed mode it certainly is if something is in front.

since i bound it to F12, the window would always be on top since it has to have focus in order to accept the key press in the first place.

some window managers don’t necessary put the focused window on top so yes it migth be a problem :slight_smile:

i tried what you suggested, but all it gave me was a white image. any ideas?

[quote]some window managers don’t necessary put the focused window on top so yes it migth be a problem :slight_smile:
[/quote]
I’m one of those “sloppy” focus kinda guys where the focus follows the mouse even if the window is obscured.

[quote]i tried what you suggested, but all it gave me was a white image. any ideas?
[/quote]
Nope, it seems like a straight forward way to take a screen shot but I haven’t put anymore thought into it beyond this thread.

I could have sworn that the custom Graphics hack is how people were getting getting swing to work in an OpenGL game. Oh well.

UPDATE: I guess you could look at the source for the paint method to see what’s up if one really cared.