1+ import javax .imageio .ImageIO ;
2+ import java .awt .Component ;
3+ import java .awt .GraphicsDevice ;
4+ import java .awt .GraphicsEnvironment ;
5+ import java .awt .Rectangle ;
6+ import java .awt .Robot ;
7+ import java .awt .Toolkit ;
8+ import java .awt .image .BufferedImage ;
9+ import java .io .File ;
10+ import org .junit .Test ;
11+
12+ import static org .junit .Assert .assertTrue ;
13+
14+ public class ScreenshotTest {
15+
16+ @ Test
17+ public void takeScreenshotOfMainScreen () throws Exception {
18+ Rectangle screenRect = new Rectangle (Toolkit .getDefaultToolkit ().getScreenSize ());
19+ BufferedImage capture = new Robot ().createScreenCapture (screenRect );
20+ File imageFile = new File ("single-screen.bmp" );
21+ ImageIO .write (capture , "bmp" , imageFile );
22+ assertTrue (imageFile .exists ());
23+ imageFile .delete ();
24+ }
25+
26+ @ Test
27+ public void takeScreenshotOfAllScreens () throws Exception {
28+ GraphicsEnvironment ge = GraphicsEnvironment .getLocalGraphicsEnvironment ();
29+ GraphicsDevice [] screens = ge .getScreenDevices ();
30+ Rectangle allScreenBounds = new Rectangle ();
31+ for (GraphicsDevice screen : screens ) {
32+ Rectangle screenBounds = screen .getDefaultConfiguration ().getBounds ();
33+ allScreenBounds .width += screenBounds .width ;
34+ allScreenBounds .height = Math .max (allScreenBounds .height , screenBounds .height );
35+ }
36+ BufferedImage capture = new Robot ().createScreenCapture (allScreenBounds );
37+ File imageFile = new File ("all-screens.bmp" );
38+ ImageIO .write (capture , "bmp" , imageFile );
39+ assertTrue (imageFile .exists ());
40+ imageFile .delete ();
41+ }
42+
43+ @ Test
44+ public void makeScreenshot (Component component ) throws Exception {
45+ Rectangle componentRect = component .getBounds ();
46+ BufferedImage bufferedImage = new BufferedImage (componentRect .width , componentRect .height , BufferedImage .TYPE_INT_ARGB );
47+ component .paint (bufferedImage .getGraphics ());
48+ File imageFile = new File ("component-screenshot.bmp" );
49+ ImageIO .write (bufferedImage , "bmp" , imageFile );
50+ assertTrue (imageFile .exists ());
51+ imageFile .delete ();
52+ }
53+
54+ }
0 commit comments