boolean running = false;
Rectangle rect = new Rectangle(10, 10, 80, 80);
JButton b = new JButton("Misca-te!");;
boolean shouldClearRect = false;
String path = new String();
BufferedImage i;
int x = 0;
double a = x;
boolean q = true;
public Thread th;
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.RED);
g.drawImage(i, x, 0, null);
path = "/Xture/apple.png";
i = game2.loadImage(path);
this.add(b);
}
public void update(){
x+= 1;
}
public void run(){
int fps = 60;
double timepertick = 1000000000 / fps;
double delta = 0;
long now;
long lasttime = System.nanoTime();
long timer = 0;
int ticks = 0;
while(true){
now = System.nanoTime();
delta += (now - lasttime)/ timepertick;
timer += now - lasttime;
lasttime = now;
if(delta >= 1){
update();
ticks++;
delta--;
}
if(timer >= 1000000000){
System.out.println(ticks);
ticks = 0;
timer = 0;
}
}
}
public void start(){
running = true;
th = new Thread(this);
th.start();
}
public static BufferedImage loadImage(String path){
try {
return ImageIO.read(game2.class.getResource(path));
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
return null;
}
This code needs to move the image by 1 pixel per second. But if I run it, it moves more than 1 pixel at a time and then it stops, and yet every second it writes "60 fps" in the console. Is something wrong with my code, or does my laptop have problems?
P.S.: the JFrame
is in the main class