Search code examples
javascreenshotawtrobot

display screenshots and split them into two realtime


I am new at Java.

I am trying to display the screenshot of the present screen and update it realtime. It is working fine if i am displaying it just once But for my college project I am supposed to display the same screenshot on two adjacent screens.

I am not able to figure out how to implement this.

I found two codes and was trying to implement them together so that I get the required outcome. http://www.ivoronline.com/Coding/Languages/JAVA/Tutorials/JAVA%20-%20File%20-%20Image%20-%20Display%20Multiple%20Images.php

Capturing and displaying an image using Java

This is what my present code is.

     import javax.swing.*;

     import java.awt.Rectangle;
     import java.awt.Robot;
     import java.awt.image.BufferedImage;

     public class OrionCode_v02 {

     public static void main(String[] args) throws Exception {
     Robot robot = new Robot();

    //JPanel panel = new JPanel();

    JFrame theGUI = new JFrame();
    //theGUI.getContentPane().add (panel);
    theGUI.setTitle("TestApp");
    theGUI.setSize(640, 720);        
    theGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    theGUI.setVisible(true);

    JLabel picLabel = new JLabel();
    JLabel picLabel2 = new JLabel();
    theGUI.add(picLabel);
    theGUI.add(picLabel2);

    while (true) 
    {
        BufferedImage screenShot = robot.createScreenCapture(new Rectangle(0,0,320,720)); // x-coord, y-coord, width, height
        BufferedImage screenShot1 = robot.createScreenCapture(new Rectangle(320,0,320,720)); // x-coord, y-coord, width, height

        picLabel.setIcon(new ImageIcon(screenShot1)); 
        picLabel2.setIcon(new ImageIcon(screenShot));

        theGUI.add(picLabel);
        theGUI.add(picLabel2);


      /*  
        panel.add (new JLabel (new ImageIcon (screenShot)));
        panel.add (new JLabel (new ImageIcon (screenShot1)));
    */
    }
}

}

It doesn't display screenshot1. only displays the screenshot. If I swap the two commands of picLabel.setIcon, then it displays screenshot1.

I need to display both the screenshots together. How do I go about it?


Solution

  • JFrame has BorderLayout by default, which makes add(Component) method to add component always to center part of frame by default, replacing any components already put there. So you only have picLabel2 in frame. You can add components to specific parts by using overloaded add:

    theGUI.add(picLabel, BorderLayout.WEST);
    theGUI.add(picLabel2, BorderLayout.EAST);
    

    You also have unnecessary add() calls inside your loop.