I have created a software timer and when it goes zero it's going to start a new login screen. The problem is the login comes over and over again. How to stop this?
class DisplayCountdown extends TimerTask {
int seconds = 0005;
public void run() {
if (seconds > 0) {
int hr = (int) (seconds / 3600);
int rem = (int) (seconds % 3600);
int mn = rem / 60;
int sec = rem % 60;
String hrStr = (hr < 10 ? "0" : "") + hr;
String mnStr = (mn < 10 ? "0" : "") + mn;
String secStr = (sec < 10 ? "0" : "") + sec;
seconds--;
lab.setText(hrStr + " : " + mnStr + " : " + secStr + "");
} else {
login ty = new login();
login.scname.setText(scname.getText());
login.scnum.setText(scnum.getText());
login.mar.setText(jTextField1.getText());
ty.setVisible(true);
dispose();
}
}
}
3 Answers 3
This is violating the single thread rules of Swing - Updating the UI out side the context of the Event Dispatching Thread.
Instead of TimerTask, you should be using a javax.swing.Timer.
javax.swing.Timer swingTimer = new javax.swing.Timer(500, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (seconds > 0) {
//...
} else {
((javax.swing.Timer)evt.getSource()).stop();
//...
}
}
});
Take a look at Concurrency in Swing
Comments
It is not clear what the code is but can't you use the "cancel()" method of the TimerTask class to cancel it?
Comments
You need to keep reference of previous Login Screen and dispose it before making a new one;