I have a java program that's should be doing something very simple. It contains a JPanel
, on which repaint()
is called 30 times each second. This JPanel
overrides the paintComponent()
method, and in this overwritten method, I take a BufferedImage
and draw it to the JPanel.
This BufferedImage
consists of a black image with a somewhat smaller blue rectangle inside of it. This displays, but the problem is that the left side, 50-80 pixels or so, of the screen flickers. On the leftmost part of what should be the blue rectangle, some of the pixels will sometimes appear black instead, as though there's some black overlay extending from the left side of the screen covering it, that flickers a bit each frame.
I wouldn't think just drawing a rectangle would be so consuming that it would cause graphical bugs with something like this; is it? I can't figure out why this would be happening, so do any of you have any idea what would cause a black "flicker" on the left of either a BufferedImage
or a Graphics2D
?
'Runnable example(please add the imports)':
public class Panel extends JPanel{
public int width, height;
public long lastTime;
public BufferedImage canvas;
public Panel(int a, int b){
width = a;
height = b;
canvas = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
lastTime = System.currentTimeMillis();
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g.drawImage(canvas, 0, 0, this);
}
public void drawRect(int startX, int startY, int w, int h, int color){
for(int i=0; i<w; i++){
for(int j=0; j<h; j++){
canvas.setRGB(i + startX, j + startY, color);
}
}
}
public void render(){
drawRect(0, 0, width, height, 0x000000);
drawRect(10, 10, width - 20, height - 20, 0x0000ff);
}
public void update(){
int delta = (int)(System.currentTimeMillis() - lastTime);
if(delta >= 1000 / 30){
render();
lastTime = System.currentTimeMillis();
}
}
//in a different class, contains main()
public class Main{
public static Panel pan;
public static void main(String[] args){
JFrame frame = new JFrame();
Container c = frame.getContentPane();
c.setPreferredSize(500, 500);
pan = new Panel(500, 500);
frame.add(pan);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
new runThread().run();
}
class runThread extends Thread{
public void run(){
while(true){
pan.update();
}
}
}
}