Example usage for java.awt Robot createScreenCapture

List of usage examples for java.awt Robot createScreenCapture

Introduction

In this page you can find the example usage for java.awt Robot createScreenCapture.

Prototype

public synchronized BufferedImage createScreenCapture(Rectangle screenRect) 

Source Link

Document

Creates an image containing pixels read from the screen.

Usage

From source file:RobotTest.java

/**
 * Runs a sample test procedure/*from ww  w  . j a v a2  s.co  m*/
 * 
 * @param robot
 *          the robot attached to the screen device
 */
public static void runTest(Robot robot) {
    // simulate a space bar press
    robot.keyPress(' ');
    robot.keyRelease(' ');

    // simulate a tab key followed by a space
    robot.delay(2000);
    robot.keyPress(KeyEvent.VK_TAB);
    robot.keyRelease(KeyEvent.VK_TAB);
    robot.keyPress(' ');
    robot.keyRelease(' ');

    // simulate a mouse click over the rightmost button
    robot.delay(2000);
    robot.mouseMove(200, 50);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);

    // capture the screen and show the resulting image
    robot.delay(2000);
    BufferedImage image = robot.createScreenCapture(new Rectangle(0, 0, 400, 300));

    ImageFrame frame = new ImageFrame(image);
    frame.setVisible(true);
}

From source file:org.sugarcrm.voodoodriver.Utils.java

/**
 * Take a screen shot and save it to the specified file.
 *
 * @param outputFile  file to save the screenshot into
 * @param reporter    {@link Reporter} object for logging errors
 * @param logOK whether logging to reporter is OK.  false if this
 *              is called from a reporter object.
 * @return whether the screenshot was taken successfully
 *//*from   www .  ja  v a  2 s .  c o  m*/

public static boolean takeScreenShot(String outputFile, Reporter reporter, boolean logOK) {
    Robot r = null;

    reporter.Log("Taking Screenshot.");

    File tmp = new File(outputFile);
    if (tmp.exists() && logOK) {
        String msg;
        msg = String.format("Existing screenshot '%s' will be overwritten.", outputFile);
        reporter.Warn(msg);
    }

    try {
        r = new Robot();
    } catch (java.awt.AWTException e) {
        if (logOK) {
            reporter.ReportError("Screenshot failed (running headless?)");
            reporter.ReportException(e);
        }
        return false;
    }

    Rectangle rec = new Rectangle();
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    dim.setSize(dim);
    rec.setSize(dim);
    BufferedImage img = r.createScreenCapture(rec);

    try {
        ImageIO.write(img, "png", new File(outputFile));
    } catch (java.io.IOException e) {
        if (logOK) {
            reporter.ReportError("Screenshot failed (I/O Error)");
            reporter.ReportException(e);
        }
        return false;
    }

    reporter.Log(String.format("Screenshot file: %s", outputFile));
    reporter.Log("Screenshot finished.");

    return true;
}

From source file:com.qspin.qtaste.testapi.impl.generic.UtilityImpl.java

public void createScreenshot(String fileName) throws QTasteException {
    try {/*from   w  w w .ja v  a2 s .  c o  m*/
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle screenRectangle = new Rectangle(screenSize);
        Robot robot = new Robot();
        BufferedImage image = robot.createScreenCapture(screenRectangle);
        ImageIO.write(image, "png", new File(fileName));
    } catch (Exception e) {
        throw new QTasteException("Error in createScreenshot: " + e.getMessage());
    }
}

From source file:com.github.srec.rec.DefaultScreenShot.java

public String capture(String subdir, Rectangle screenRect, Robot robot) {
    BufferedImage image = robot.createScreenCapture(screenRect);
    if (image == null) {
        return null;
    }/*w w w .  j  a  v  a2  s  . c o m*/
    String captureFileName = "screenshot-" + counter++ + ".png";
    String pathname = PropertiesReader.getProperties().getProperty(PropertiesReader.SCREENSHOTS_DIR);
    if (isBlank(pathname)) {
        pathname = "target/screenshots";
    }
    if (!isBlank(subdir)) {
        pathname = pathname + File.separator + subdir;
    }
    createScreenshotDirectory(pathname);
    String finalFileName = pathname + File.separator + captureFileName;
    try {
        ImageIO.write(image, "png", new File(finalFileName));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return finalFileName;
}

From source file:org.jboss.arquillian.extension.screenRecorder.ScreenRecorder.java

private BufferedImage getDesktopScreenshot() {
    try {//from ww  w  . j ava2s . c o  m
        Robot robot = new Robot();
        Rectangle captureSize = new Rectangle(screenBounds);
        return robot.createScreenCapture(captureSize);
    } catch (AWTException e) {
        logger.error("Exception occured while taking screenshot for video record", e);
        return null;
    }
}

From source file:com.ixxus.IxxusAbstractTest.java

public void saveOsScreenShot(String methodName) throws IOException, AWTException {
    Robot robot = new Robot();
    BufferedImage screenShot = robot
            .createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
    ImageIO.write(screenShot, "png", new File("target/webdriver-" + methodName + "_OS" + ".png"));
}

From source file:io.github.dsheirer.gui.SDRTrunk.java

/**
 * Initialize the contents of the frame.
 *///from   w  ww.  jav a 2s .  c o  m
private void initGUI() {
    mMainGui.setLayout(new MigLayout("insets 0 0 0 0 ", "[grow,fill]", "[grow,fill]"));

    /**
     * Setup main JFrame window
     */
    mTitle = SystemProperties.getInstance().getApplicationName();
    mMainGui.setTitle(mTitle);
    mMainGui.setBounds(100, 100, 1280, 800);
    mMainGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Set preferred sizes to influence the split
    mSpectralPanel.setPreferredSize(new Dimension(1280, 300));
    mControllerPanel.setPreferredSize(new Dimension(1280, 500));

    mSplitPane = new JideSplitPane(JideSplitPane.VERTICAL_SPLIT);
    mSplitPane.setDividerSize(5);
    mSplitPane.add(mSpectralPanel);
    mSplitPane.add(mControllerPanel);

    mBroadcastStatusVisible = SystemProperties.getInstance().get(PROPERTY_BROADCAST_STATUS_VISIBLE, false);

    //Show broadcast status panel when user requests - disabled by default
    if (mBroadcastStatusVisible) {
        mSplitPane.add(getBroadcastStatusPanel());
    }

    mMainGui.add(mSplitPane, "cell 0 0,span,grow");

    /**
     * Menu items
     */
    JMenuBar menuBar = new JMenuBar();
    mMainGui.setJMenuBar(menuBar);

    JMenu fileMenu = new JMenu("File");
    menuBar.add(fileMenu);

    JMenuItem logFilesMenu = new JMenuItem("Logs & Recordings");
    logFilesMenu.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            try {
                Desktop.getDesktop().open(getHomePath().toFile());
            } catch (Exception e) {
                mLog.error("Couldn't open file explorer");

                JOptionPane.showMessageDialog(mMainGui,
                        "Can't launch file explorer - files are located at: " + getHomePath().toString(),
                        "Can't launch file explorer", JOptionPane.ERROR_MESSAGE);
            }
        }
    });
    fileMenu.add(logFilesMenu);

    JMenuItem settingsMenu = new JMenuItem("Icon Manager");
    settingsMenu.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            mIconManager.showEditor(mMainGui);
        }
    });
    fileMenu.add(settingsMenu);

    fileMenu.add(new JSeparator());

    JMenuItem exitMenu = new JMenuItem("Exit");
    exitMenu.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            System.exit(0);
        }
    });

    fileMenu.add(exitMenu);

    JMenu viewMenu = new JMenu("View");

    viewMenu.add(new BroadcastStatusVisibleMenuItem(mControllerPanel));

    menuBar.add(viewMenu);

    JMenuItem screenCaptureItem = new JMenuItem("Screen Capture");

    screenCaptureItem.setMnemonic(KeyEvent.VK_C);
    screenCaptureItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.ALT_MASK));

    screenCaptureItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            try {
                Robot robot = new Robot();

                final BufferedImage image = robot.createScreenCapture(mMainGui.getBounds());

                SystemProperties props = SystemProperties.getInstance();

                Path capturePath = props.getApplicationFolder("screen_captures");

                if (!Files.exists(capturePath)) {
                    try {
                        Files.createDirectory(capturePath);
                    } catch (IOException e) {
                        mLog.error("Couldn't create 'screen_captures' " + "subdirectory in the "
                                + "SDRTrunk application directory", e);
                    }
                }

                String filename = TimeStamp.getTimeStamp("_") + "_screen_capture.png";

                final Path captureFile = capturePath.resolve(filename);

                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            ImageIO.write(image, "png", captureFile.toFile());
                        } catch (IOException e) {
                            mLog.error("Couldn't write screen capture to " + "file [" + captureFile.toString()
                                    + "]", e);
                        }
                    }
                });
            } catch (AWTException e) {
                mLog.error("Exception while taking screen capture", e);
            }
        }
    });

    menuBar.add(screenCaptureItem);
}

From source file:com.limegroup.gnutella.gui.notify.AnimatedWindow.java

private void prepareAnimation(Point location) {
    if (animationImage != null) {
        // already have an image, this could be the case if a hide animation
        // is started while a show animation is still in progress or the
        // other/* www .ja v a  2  s  . co m*/
        // way around
        return;
    }

    // reset window to original size to capture all content
    pack();
    Dimension size = getSize();

    if (mode.needsBackgroundImage() && backgroundImage == null) {
        try {
            Robot robot = new Robot();
            backgroundImage = robot.createScreenCapture(new Rectangle(location, size));
        } catch (AWTException e) {
            LOG.warn("Could not capture background image", e);
            backgroundImage = null;
        }
    }

    animationImage = getGraphicsConfiguration().createCompatibleImage(size.width, size.height);
    Graphics grahpics = animationImage.getGraphics();
    getContentPane().paint(grahpics);
    grahpics.dispose();
}

From source file:de.mycrobase.jcloudapp.Main.java

private BufferedImage takeScreenshot() {
    try {/*from  www.  j a  v  a  2  s . co  m*/
        Robot robot = new Robot();
        Rectangle captureSize = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
        return robot.createScreenCapture(captureSize);
    } catch (AWTException ex) {
        System.out.println(ex);
    }
    return null;
}

From source file:com.photon.phresco.framework.rest.api.UtilService.java

@POST
@Path("/sendErrorReport")
@Produces(MediaType.APPLICATION_JSON)// ww  w.j  a v a  2s  .com
public Response sendErrorReport(String errorReport, @QueryParam("emailId") String emailId,
        @QueryParam("username") String username) throws PhrescoException {
    ResponseInfo<String> responseData = new ResponseInfo<String>();
    File screenShot = new File(Utility.getPhrescoTemp(), FrameworkConstants.TEMP_ERRORIMG_FILE);
    File logFile = new File(Utility.getPhrescoTemp(), FrameworkConstants.TEMP_ERROR_FILE);
    FileWriter fileWriter = null;
    UpgradeManagerImpl build = new UpgradeManagerImpl();
    String buildNumber = build.getCurrentVersion();
    try {
        fileWriter = new FileWriter(logFile);
        fileWriter.write(errorReport);
        fileWriter.close();
        // For screen shot
        Robot robot = new Robot();
        BufferedImage bi = robot.createScreenCapture(new Rectangle(1000, 700));
        ImageIO.write(bi, "jpg", new File(Utility.getPhrescoTemp(), FrameworkConstants.TEMP_ERRORIMG_FILE));

        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("framework.config");
        Properties prop = new Properties();
        prop.load(resourceAsStream);
        String group = prop.getProperty("phresco.support.mailIds");
        String[] groupp = group.split(",");
        Utility.sendTemplateEmail(groupp, emailId, username, MAIL_SUBJECT, logFile.getPath(), MAIL_ID,
                MAIL_PASSWORD, null, screenShot.getPath(), buildNumber);
        ResponseInfo<String> finalOutput = responseDataEvaluation(responseData, null, null,
                RESPONSE_STATUS_SUCCESS, PHR14C00001);
        return Response.status(Status.OK).entity(finalOutput).header("Access-Control-Allow-Origin", "*")
                .build();
    } catch (IOException ex) {
        throw new PhrescoException(ex);
    } catch (Exception e) {
        ResponseInfo<String> finalOutput = responseDataEvaluation(responseData, e, null, RESPONSE_STATUS_ERROR,
                PHR14C10001);
        return Response.status(Status.OK).entity(finalOutput).header("Access-Control-Allow-Origin", "*")
                .build();
    } finally {
        Utility.closeStream(fileWriter);
        if (logFile.exists()) {
            FileUtil.delete(logFile);
        }
        if (screenShot.exists()) {
            FileUtil.delete(screenShot);
        }
    }
}