I'm trying to render an Image with a BufferStrategy and Graphics2D. The Code works well, but the Image is flickering. Before I tested it with Graphics2D, I tried only with Graphics and the Frame was flickering crazy. Here's the Code:
public Main() {
x = 0;
Dimension size = new Dimension(sx, sy);
setPreferredSize(size);
frame = new JFrame();
ImageIcon player2 = new ImageIcon("res/gfx/char.png");
player = player2.getImage();
addKeyListener(new AL());
time = new Timer(5, this);
time.start();
}
public synchronized void start() {
running = true;
thread = new Thread(this, "Display");
thread.start();
}
public synchronized void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run() {
while (running) {
render();
update();
}
}
public void render() {
BufferStrategy bs = getBufferStrategy();
if (bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, 800, 600);
g2d.drawImage(player, x, 350, null);
g.dispose();
bs.show();
}
(Sorry for my bad english)
I think you are drawing the image directly on jframe. Try to use a middle level container component like JPanel and draw the image over it and add the panel to the frame. Direct drawing causes flickering effect.