I am trying to make a little game, a plane is up and when i click the down arrow it drops a bomb. If bomb hit the target it changes its place etc...
public void paint(Graphics p) {
p.setColor(c);
p.drawLine(0, 650, 1000, 650);
p.fillRect(x3, y3, 150, 50);
p.fillOval(x2, y2, 30, 30);
p.drawImage(image, x, y, null);
if (x < 1000) {
x = x + 10;
}
if (x > 750) {
x = 0;
}
try {
Thread.sleep(40);
} catch (InterruptedException ignored) {
}
if (bo==true) {
x2 = x2 + z;
y2 = y2 + 8;
}
if (y2 > 450 && z != 0) {
z--;
}
if (y2 > 620) {
x2 =- 100;
y2 =- 100;
}
if (y2 > 610 && x2 < x3 + 150 && x2 > x3) {
x3 = x3 + 100;
}
repaint(1);
}
But the problem is at first everything is normal after 1 or 2 seconds fps is like 10, sometimes i cant see the objects, i saw another topic about using timer but i dont want to solve it with timer and even i dont know if i could. I wonder if its about my computer or ide.
First of all, do not Override
paint()
method. Override
paintComponent(Graphics g)
method (and do not forget to call super.paintComponent(g)
.
Secondly, using Thread.sleep()
method in EDT (hopefully, you start your application, using SwingUtilities#invokeLater
) is bad idea, since all events will stop taking place (with few words, the whole GUI will freeze).
You should use a swing Timer instead.
Finally, do not call repaint()
inside paintComponent
, because repaint()
will call paintComponent
again, and it will be an endless loop. You should repaint the component in Timer`s action listener.