0

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();
        }
    }
}
4

3 回答 3

1

这违反了 Swing 的单线程规则 - 在事件调度线程的上下文之外更新 UI。

而不是TimerTask,您应该使用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();
            //...
        }
    }
});

看看Swing 中的并发性

于 2013-10-07T05:53:08.717 回答
0

不清楚代码是什么,但不能用TimerTask类的“cancel()”方法取消吗?

于 2013-10-07T05:50:59.207 回答
0

您需要保留以前登录屏幕的参考并在制作新屏幕之前将其处理掉;

于 2013-10-07T06:06:10.150 回答