I am trying to figure out why this code cause the window responsiveness to become really laggy.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GamePanel extends JPanel implements Runnable{
private Game game = Game.getInstance();
private Image buffer = null;
private int width,height;
public GamePanel(JFrame f){
width = 650;
height = 480;
this.setBackground(Color.black);
this.setPreferredSize(new Dimension(width,height));
this.setDoubleBuffered(false);
this.setFocusable(true);
this.requestFocus();
f.getContentPane().add(this);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* Main loop into game
*/
public void run(){
//create buffer
buffer = createImage(width,height);
while(!game.over()){
game.update();
game.render(buffer);
paintScreen();
//need frame rate control here
}
}
private void paintScreen() {
Graphics g = null;
g = this.getGraphics();
g.drawImage(buffer, 0, 0, null);
Toolkit.getDefaultToolkit().sync();
}
public void paintComponents(Graphics g){
super.paintComponents(g);
if(buffer != null) g.drawImage(buffer,0,0,null);
}
public static void main(String[] args){
JFrame jframe = new JFrame();
GamePanel panel = new GamePanel(jframe);
Thread game = new Thread(panel);
game.start();
jframe.setVisible(true);
}
}