So I have made a program where I made so a clock appears when running the program. so. When I press a button "Start" a clock should go random inside a bounds and go as a clock aswell (I mean like digital, 15:18:19, 15:18:20). but my problem is now whenever I press the program. the clock stays on the same spot and when changing the sleep time to etc. 500. then it starts to move but the time semms to go alot faster (since it should sleep 1000). however I don't see the problem in the code where it should go. but however maybe some of you could help me with that.
public void startClock() {
Thread t2 = new Thread() {
public void run() {
if (clocking) {
Random rand = new Random();
while(clocking){
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
movingClock.setText(hour + ":" + minute + ":" + second);
int x = rand.nextInt(100) + 1;
int y = rand.nextInt(100) + 1;
movingClock.setBounds(x, y, 150, 150);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
t2.start();
}
where clocking is = true. because whenever I press the button. I turn it the clocking to true and then run the startClock().
but as I said before. the digital clock only goes randomly if I change the sleep time below 500. and how can I make it work if it's sleep(1000)?
EDIT NEW ONE:
public void startMoving() {
Thread t1 = new Thread() {
public void run() {
if (moving) {
Random random = new Random();
while (moving) {
int x = random.nextInt(100) + 1;
int y = random.nextInt(100) + 1;
movingDisplay.setBounds(x, y, 150, 150);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
t1.start();
}
public void startClock() {
Thread t2 = new Thread() {
public void run() {
if (clocking) {
Random rand = new Random();
while(clocking){
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
movingClock.setText(hour + ":" + minute + ":" + second);
int x = rand.nextInt(100) + 1;
int y = rand.nextInt(100) + 1;
movingClock.setBounds(x, y, 150, 150);
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
movingClock.setText(hour + ":" + minute + ":" + second);
movingClock.setBounds(x, y, 150, 150);
movingDisplay.setBounds(x, y, 150, 150);
}
} );
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
t2.start();
}