JRuby Toolkit Robot example - how take a screenshot of your desktop

Here's some sample JRuby code that I just used to take a screenshot of my desktop. It uses the Toolkit and Robot classes from Java to make it all happen. It could probably be a little shorter, but I don't know much about JRuby yet. I also had a problem getting the Java File class to work properly, and referencing it as shown was the only way I could get it to work.

As you'll see from the source code, the example uses the classes mentioned to create an image (a BufferedImage) of your desktop, then saves the image as a PNG file.

#
# devdaily.com
# ruby/jruby code to create an image/screenshot of your desktop
#
require 'java'

include_class 'java.awt.Dimension'
include_class 'java.awt.Rectangle'
include_class 'java.awt.Robot'
include_class 'java.awt.Toolkit'
include_class 'java.awt.event.InputEvent'
include_class 'java.awt.image.BufferedImage'
include_class 'javax.imageio.ImageIO'

toolkit = Toolkit::getDefaultToolkit()
screen_size = toolkit.getScreenSize()
rect = Rectangle.new(screen_size)
robot = Robot.new
image = robot.createScreenCapture(rect)
f = java::io::File.new('test.png')
ImageIO::write(image, "png", f)