<p>Simple as the title states: Can you use only Java commands to take a screenshot and save it?  Or, do I need to use an OS specific program to take the screenshot and then grab it off the clipboard?</p>

[{'answer_id': 58326, 'author': 'David Citron', 'author_id': 5309, 'author_profile': 'https://Stackoverflow.com/users/5309', 'pm_score': 9, 'selected': True, 'text': '<p>Believe it or not, you can actually use <a href="http://java.sun.com/javase/6/docs/api/java/awt/Robot.html#createScreenCapture&#40;java.awt.Rectangle&#41;" rel="noreferrer"><code>java.awt.Robot</code></a> to "create an image containing pixels read from the screen." You can then write that image to a file on disk.</p>\n\n<p>I just tried it, and the whole thing ends up like:</p>\n\n<pre><code>Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());\nBufferedImage capture = new Robot().createScreenCapture(screenRect);\nImageIO.write(capture, "bmp", new File(args[0]));\n</code></pre>\n\n<p>NOTE: This will only capture the primary monitor. See <a href="http://java.sun.com/javase/6/docs/api/java/awt/GraphicsConfiguration.html" rel="noreferrer">GraphicsConfiguration</a> for multi-monitor support.</p>\n'}, {'answer_id': 10796047, 'author': 'DejanLekic', 'author_id': 876497, 'author_profile': 'https://Stackoverflow.com/users/876497', 'pm_score': 5, 'selected': False, 'text': '<p>I never liked using Robot, so I made my own simple method for making screenshots of JFrame objects:</p>\n\n<pre><code>public static final void makeScreenshot(JFrame argFrame) {\n    Rectangle rec = argFrame.getBounds();\n    BufferedImage bufferedImage = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);\n    argFrame.paint(bufferedImage.getGraphics());\n\n    try {\n        // Create temp file\n        File temp = File.createTempFile("screenshot", ".png");\n\n        // Use the ImageIO API to write the bufferedImage to a temporary file\n        ImageIO.write(bufferedImage, "png", temp);\n\n        // Delete temp file when program exits\n        temp.deleteOnExit();\n    } catch (IOException ioe) {\n        ioe.printStackTrace();\n    }\n}\n</code></pre>\n'}, {'answer_id': 17229248, 'author': 'user2503881', 'author_id': 2503881, 'author_profile': 'https://Stackoverflow.com/users/2503881', 'pm_score': 4, 'selected': False, 'text': '<pre><code>public void captureScreen(String fileName) throws Exception {\n   Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();\n   Rectangle screenRectangle = new Rectangle(screenSize);\n   Robot robot = new Robot();\n   BufferedImage image = robot.createScreenCapture(screenRectangle);\n   ImageIO.write(image, "png", new File(fileName));\n}\n</code></pre>\n'}, {'answer_id': 18156495, 'author': '11101101b', 'author_id': 875305, 'author_profile': 'https://Stackoverflow.com/users/875305', 'pm_score': 4, 'selected': False, 'text': "<p>If you'd like to capture all monitors, you can use the following code:</p>\n\n<pre><code>GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();\nGraphicsDevice[] screens = ge.getScreenDevices();\n\nRectangle allScreenBounds = new Rectangle();\nfor (GraphicsDevice screen : screens) {\n    Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();\n\n    allScreenBounds.width += screenBounds.width;\n    allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);\n}\n\nRobot robot = new Robot();\nBufferedImage screenShot = robot.createScreenCapture(allScreenBounds);\n</code></pre>\n"}, {'answer_id': 27603992, 'author': 'Nilesh Jadav', 'author_id': 3966892, 'author_profile': 'https://Stackoverflow.com/users/3966892', 'pm_score': 2, 'selected': False, 'text': '<pre><code>import java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.Rectangle;\nimport java.awt.Robot;\nimport java.awt.Toolkit;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.image.BufferedImage;\nimport java.io.File; \nimport javax.imageio.ImageIO;\nimport javax.swing.*;  \n\npublic class HelloWorldFrame extends JFrame implements ActionListener {\n\nJButton b;\npublic HelloWorldFrame() {\n    this.setVisible(true);\n    this.setLayout(null);\n    b = new JButton("Click Here");\n    b.setBounds(380, 290, 120, 60);\n    b.setBackground(Color.red);\n    b.setVisible(true);\n    b.addActionListener(this);\n    add(b);\n    setSize(1000, 700);\n}\npublic void actionPerformed(ActionEvent e)\n{\n    if (e.getSource() == b) \n    {\n        this.dispose();\n        try {\n            Thread.sleep(1000);\n            Toolkit tk = Toolkit.getDefaultToolkit(); \n            Dimension d = tk.getScreenSize();\n            Rectangle rec = new Rectangle(0, 0, d.width, d.height);  \n            Robot ro = new Robot();\n            BufferedImage img = ro.createScreenCapture(rec);\n            File f = new File("myimage.jpg");//set appropriate path\n            ImageIO.write(img, "jpg", f);\n        } catch (Exception ex) {\n            System.out.println(ex.getMessage());\n        }\n    }\n}\n\npublic static void main(String[] args) {\n    HelloWorldFrame obj = new HelloWorldFrame();\n}\n}\n</code></pre>\n'}, {'answer_id': 31083752, 'author': 'joe pelletier', 'author_id': 4088794, 'author_profile': 'https://Stackoverflow.com/users/4088794', 'pm_score': 2, 'selected': False, 'text': '<pre><code>GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();  \nGraphicsDevice[] screens = ge.getScreenDevices();       \nRectangle allScreenBounds = new Rectangle();  \nfor (GraphicsDevice screen : screens) {  \n       Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();        \n       allScreenBounds.width += screenBounds.width;  \n       allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);\n       allScreenBounds.x=Math.min(allScreenBounds.x, screenBounds.x);\n       allScreenBounds.y=Math.min(allScreenBounds.y, screenBounds.y);\n      } \nRobot robot = new Robot();\nBufferedImage bufferedImage = robot.createScreenCapture(allScreenBounds);\nFile file = new File("C:\\\\Users\\\\Joe\\\\Desktop\\\\scr.png");\nif(!file.exists())\n    file.createNewFile();\nFileOutputStream fos = new FileOutputStream(file);\nImageIO.write( bufferedImage, "png", fos );\n</code></pre>\n\n<p>bufferedImage will contain a full screenshot, this was tested with three monitors </p>\n'}, {'answer_id': 45937897, 'author': 'Muhammad Yawar', 'author_id': 4770992, 'author_profile': 'https://Stackoverflow.com/users/4770992', 'pm_score': 0, 'selected': False, 'text': '<p>You can use <code>java.awt.Robot</code> to achieve this task.</p>\n\n<p>below is the code of server, which saves the captured screenshot as image in your Directory.</p>\n\n<pre><code>import java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.ServerSocket;\nimport java.net.Socket;\nimport java.net.SocketTimeoutException;\nimport java.sql.SQLException;\nimport java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\nimport javax.imageio.ImageIO;\n\npublic class ServerApp extends Thread\n{\n       private ServerSocket serverSocket=null;\n       private static Socket server = null;\n       private Date date = null;\n       private static final String DIR_NAME = "screenshots";\n\n   public ServerApp() throws IOException, ClassNotFoundException, Exception{\n       serverSocket = new ServerSocket(61000);\n       serverSocket.setSoTimeout(180000);\n   }\n\npublic void run()\n   {\n       while(true)\n      {\n           try\n           {\n              server = serverSocket.accept();\n              date = new Date();\n                  DateFormat dateFormat = new SimpleDateFormat("_yyMMdd_HHmmss");\n              String fileName = server.getInetAddress().getHostName().replace(".", "-");\n              System.out.println(fileName);\n              BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(server.getInputStream()));\n              ImageIO.write(img, "png", new File("D:\\\\screenshots\\\\"+fileName+dateFormat.format(date)+".png"));\n              System.out.println("Image received!!!!");\n              //lblimg.setIcon(img);\n          }\n         catch(SocketTimeoutException st)\n         {\n               System.out.println("Socket timed out!"+st.toString());\n //createLogFile("[stocktimeoutexception]"+stExp.getMessage());\n                  break;\n             }\n             catch(IOException e)\n             {\n                  e.printStackTrace();\n                  break;\n         }\n         catch(Exception ex)\n        {\n              System.out.println(ex);\n        }\n      }\n   }\n\n   public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception{\n          ServerApp serverApp = new ServerApp();\n          serverApp.createDirectory(DIR_NAME);\n          Thread thread = new Thread(serverApp);\n            thread.start();\n   }\n\nprivate void createDirectory(String dirName) {\n    File newDir = new File("D:\\\\"+dirName);\n    if(!newDir.exists()){\n        boolean isCreated = newDir.mkdir();\n    }\n }\n} \n</code></pre>\n\n<p>And this is Client code which is running on thread and after some minutes it is capturing the screenshot of user screen.</p>\n\n<pre><code>package com.viremp.client;\n\nimport java.awt.AWTException;\nimport java.awt.Dimension;\nimport java.awt.Rectangle;\nimport java.awt.Robot;\nimport java.awt.Toolkit;\nimport java.awt.image.BufferedImage;\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\n\npublic class ClientApp implements Runnable {\n    private static long nextTime = 0;\n    private static ClientApp clientApp = null;\n    private String serverName = "192.168.100.18"; //loop back ip\n    private int portNo = 61000;\n    //private Socket serverSocket = null;\n\n    /**\n     * @param args\n     * @throws InterruptedException \n     */\n    public static void main(String[] args) throws InterruptedException {\n        clientApp = new ClientApp();\n        clientApp.getNextFreq();\n        Thread thread = new Thread(clientApp);\n        thread.start();\n    }\n\n    private void getNextFreq() {\n        long currentTime = System.currentTimeMillis();\n        Random random = new Random();\n        long value = random.nextInt(180000); //1800000\n        nextTime = currentTime + value;\n        //return currentTime+value;\n    }\n\n    @Override\n    public void run() {\n        while(true){\n            if(nextTime &lt; System.currentTimeMillis()){\n                System.out.println(" get screen shot ");\n                try {\n                    clientApp.sendScreen();\n                    clientApp.getNextFreq();\n                } catch (AWTException e) {\n                    // TODO Auto-generated catch block\n                    System.out.println(" err"+e);\n                } catch (IOException e) {\n                    // TODO Auto-generated catch block\n                    e.printStackTrace();\n                } catch(Exception e){\n                    e.printStackTrace();\n                }\n\n            }\n            //System.out.println(" statrted ....");\n        }\n\n    }\n\n    private void sendScreen()throws AWTException, IOException {\n           Socket serverSocket = new Socket(serverName, portNo);\n             Toolkit toolkit = Toolkit.getDefaultToolkit();\n             Dimension dimensions = toolkit.getScreenSize();\n                 Robot robot = new Robot();  // Robot class \n                 BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));\n                 ImageIO.write(screenshot,"png",serverSocket.getOutputStream());\n                 serverSocket.close();\n    }\n}\n</code></pre>\n'}, {'answer_id': 53084575, 'author': 'MisterParser', 'author_id': 3123946, 'author_profile': 'https://Stackoverflow.com/users/3123946', 'pm_score': 0, 'selected': False, 'text': '<p>Toolkit returns pixels based on PPI, as a result, a screenshot is not created for the entire screen when using PPI> 100% in Windows.\nI propose to do this:</p>\n\n<pre><code>DisplayMode displayMode = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0].getDisplayMode();\nRectangle screenRectangle = new Rectangle(displayMode.getWidth(), displayMode.getHeight());\nBufferedImage screenShot = new Robot().createScreenCapture(screenRectangle);\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/58305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2598/']