Thread safe double buffering
- by kdavis8
I am trying to implement a draw map method that will draw the tiled image across the surface of the component. I'm having issue with this code. The double buffering does not seem to be working, because the sprite flickers like crazy;
my source code:
package myPackage;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class GameView extends JFrame implements Runnable {
public BufferedImage backbuffer;
public Graphics2D g2d;
public Image img;
Thread gameloop;
Scene scene;
public GameView() {
super("Game View");
setSize(600, 600);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
backbuffer = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_RGB);
g2d = backbuffer.createGraphics();
Toolkit tk = Toolkit.getDefaultToolkit();
img = tk.getImage(this.getClass().getResource("cage.png"));
scene = new Scene(g2d, this);
gameloop = new Thread(this);
gameloop.start();
}
public static void main(String args[]) {
new GameView();
}
public void paint(Graphics g) {
g.drawImage(backbuffer, 0, 0, this);
repaint();
}
@Override
public void run() {
// TODO Auto-generated method stub
Thread t = Thread.currentThread();
while (t == gameloop) {
scene.getScene("dirtmap");
g2d.drawImage(img, 80, 80,this![enter image description here][1]);
}
}
private void drawScene(String string) {
// TODO Auto-generated method stub
// g2d.setColor(Color.white);
// g2d.fillRect(0, 0, getWidth(), getHeight());
scene.getScene(string);
}
}
package myPackage;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
public class Scene {
Graphics g2d;
Component c;
boolean loaded = false;
public Scene(Graphics2D gr, Component co) {
g2d = gr;
c = co;
}
public void getScene(String mapName) {
Toolkit tk = Toolkit.getDefaultToolkit();
Image tile = tk.getImage(this.getClass().getResource("dirt.png"));
// g2d.setColor(Color.red);
for (int y = 0; y <= 18; y++) {
for (int x = 0; x <= 18; x += 1) {
g2d.drawImage(tile, x * 32, y * 32, c);
}
}
loaded = true;
}
}