package demo;
import java.awt.*;
import java.awt.image.*;
import java.util.*;
import javax.swing.*;
public class ScreenCapturingThread extends Thread{
public ScreenCapturingThread(Vector<BufferedImage> screenShots,
int frameRate,
Icon cursor,
Rectangle recordingArea){
this.screenShots = screenShots;
this.frameRate = frameRate;
this.cursor = cursor;
this.recordingArea = recordingArea;
try{
bot = new Robot();
}catch(Exception e){
System.out.println(e);
}
calculateSleepTime();
}
@Override
public void run(){
while(keepCapturing == true){
try{
screenShots.add(takeScreenShot());
sleep(sleepTime);
keepCapturing = false; //take only one shot
System.out.println("here");
JFrame frame = new JFrame();
frame.setSize(recordingArea.width,recordingArea.height);
frame.getGraphics().drawImage(screenShots.firstElement(), 0, 0,frame);
frame.repaint();
frame.setVisible(true);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
public BufferedImage takeScreenShot(){
p = m.getPointerInfo();
Point location = p.getLocation();
image = bot.createScreenCapture(recordingArea);
if(cursor!=null){
Graphics g = image.getGraphics();
g.drawImage(((ImageIcon)cursor).getImage(), location.x,location.y,null);
}
return image;
}
public void stopIt(){
keepCapturing = false;
}
public void calculateSleepTime(){
sleepTime = 1/frameRate;
}
public static void main(String[] args) {
Vector<BufferedImage> bufferedImages = new Vector<>(100);
int frameRate = 10;
Icon cursor = (Icon) new ImageIcon("src/images/blackCursor.png");
Rectangle r = new Rectangle(1280,800);
ScreenCapturingThread sc = new ScreenCapturingThread(bufferedImages,frameRate,cursor,r);
sc.start();
}
Vector<BufferedImage> screenShots;
int frameRate;
long sleepTime;
boolean keepCapturing = true;
Icon cursor;
Rectangle recordingArea;
Robot bot;
MouseInfo m;
PointerInfo p;
BufferedImage image;
}
Explanation
I have designed thread to go along with my screen recorder but I decided to test it first. This is what it is supposed to do:
run() ends, draw this on the JFrame so I can see what has been captured. Problem
I keep getting a NullPointerException at
frame.getGraphics().drawImage(screenShots.firstElement(), 0, 0,frame);
I don’t know what is going wrong.
If you could please find out the bug?
Update:

Now although the NullPointerException is gone, the frame is blank while it is not supposed to be
JFramewill not provide you with anyGraphicsuntil it is shown.If you want to draw before
JFrameis shown you never should do like this:because as Andrew Thompson has correctly written:
instead you’ll be better off doing something like below: