I may be wrong but isn't this a code that tells the thread to stop like when the times up the thread close like destroy();?
Actually, i did not think when and how you will stop the thread there. It is easy, since you will a reference to your thread object in JFrame. You will just implement a method like stopThread() in your thread and call that method from your JFrame whenever you need.
So in this scheme, you will use JFrame as the controller and the Thread will only be used to update numberOfSecondsRemaining variable and calling View class (your JFrame) whenever you want to update the display.
So the main structure will be like this (This is just to show you the structure! It will not work if you copy/paste it. You need to handle exceptions, events properly.):
class YourFrame extends JFrame {
JLabel counterLabel;
YourThread thread;
public YourFrame() {
thread = new YourThread();
}
void startButtonClicked() {
thread.start();
}
void stopButtonClicked() {
thread.stopThread();
}
void updateView(int remainingSeconds) {
counterLabel.setText(remainingSeconds);
}
}
class YourThread extends Thread {
JFrame frame;
int remainingSeconds = 100;
boolean running = true;
public YourThread(JFrame frame)
this.frame = frame;
}
public void run() {
while(running)
remainingSeconds--;
frame.updateView(remainingSeconds);
sleep(...);
}
public void stopThread() {
running = false;
}
}