I made a short Java animation that runs in a new thread. The Animation gets drawed on a canvas. It refreshes every 100ms. On some ticks the rectangle doesnt show up.(on the linked video you can see it) I tried to look for solutions on the internet but because of my standard english i didnt know how to google it the right way.
package com.felix.pack;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
public class Draw extends Canvas implements Runnable {
Thread x;
int xpos = 0;
int ypos = 0;
JFrame window;
boolean runs = false;
Graphics g;
public Draw() {
doWindow();
setPreferredSize(new Dimension(500,500));
window.add(this);
}
@Override
public void run() {
g = getGraphics();
while (runs) {
paint(g);
try {
Thread.sleep(100);
xpos +=1;
ypos +=1;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("Fail");
stop();
}
}
}
private void doWindow(){
window = new JFrame();
window.setSize(500, 500);
window.setTitle("Hey");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
public void start() {
if (runs == false) {
runs = true;
x = new Thread(this);
x.start();
} else {
System.out.println("Thread läuft bereits");
}
}
public void stop() {
runs = false;
try {
x.join();
System.out.println("Thread erfolgreich geschlossen");
} catch(Exception e) {
System.out.println("Closing thread didnt work");
}
}
public void paint(Graphics g){
g.clearRect(0, 0, 500, 500);
g.fillRect(xpos, ypos, 400, 400);
}
}
In my main Class i start the method start that is contained in this class. The parts you need to look at (i think) are the run() method and the paint method. The others are just a help to let the thread start and stop safely.
https://www.youtube.com/watch?v=pAFng8mOcOQ
Here's the video. I hope you guys can help me and im sorry if it's a dumb question :)