I have made this screenshot program in hopes of eventually making a screen recorder, but I am having trouble displaying the image for the user to see. I currently have it so that it displays and saves. When it displays it is blank, but when it saves there is a screenshot. Why is this?
package screenCapture;
import javax.imageio.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
public class CaptureScreen implements ActionListener{
public CaptureScreen (){
JFrame f = new JFrame ("Screen Capture");
JPanel pane = new JPanel ();
JButton capture = new JButton ("Capture"); capture.setActionCommand("CaptureScreen"); capture.addActionListener(this);
pane.add (capture);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add (pane);
f.setVisible(true);
f.setSize(100,100);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CaptureScreen cs = new CaptureScreen ();
}
@Override
public void actionPerformed(ActionEvent e){
// TODO Auto-generated method stub
if (e.getActionCommand().equals("CaptureScreen")){
Dimension d = Toolkit.getDefaultToolkit().getScreenSize(); // gets the screen size
Robot r;
BufferedImage bI;
try{
r= new Robot (); // creates robot not sure exactly how it works
Thread.sleep (1000); // waits 1 second before capture
bI = r.createScreenCapture(new Rectangle (d)); // tells robot to capture the screen
showPic(bI);
saveImage(bI);
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
}
private void saveImage(BufferedImage bI) {
// TODO Auto-generated method stub
try {
ImageIO.write(bI, "JPG", new File("screenShot.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void showPic(BufferedImage bI) {
// TODO Auto-generated method stub
JFrame f = new JFrame ();
JScrollPane pane = new JScrollPane ();
ImageIcon pic = new ImageIcon (bI);
JLabel l = new JLabel (pic);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pane.add (l);
f.add (pane);
f.setVisible (true);
f.setSize (700,500);
}
}