倒数计时器,向JLabel显示秒数时出错

问题描述 投票:0回答:1

我无法将秒数显示在标签中。每当我运行代码时,它应该是“ 9(分钟):59(秒)”,但它并未按计划进行,而是仅显示9分钟。

注意:我只是用一个标签显示分钟秒计时器。

这里是代码:我用过方法。

private void countDown() {
        tmClock = new Timer();
        NumberFormat nbFormat = new DecimalFormat("00");
         if (minutes == 0 && seconds == 0) {
           JOptionPane.showMessageDialog(null, "time's up!");
           tmClock.cancel();
           new Result().setVisible(true);
           this.dispose();
        } else if (seconds == 0) {
           minutes--;
           seconds = 59;
        }
         lblTime.setText(nbFormat.format(minutes) + ":" );
            String format = nbFormat.format(seconds);
        tmClock.schedule(new TimerTask() {
            @Override
            public void run() {
                seconds--;
                countDown();
            }
        }, 1000);

    }
java swing number-formatting netbeans-8
1个回答
2
投票

这里有很多问题:

  • 您使用了错误的Timer类。这是一个Swing应用程序,执行此操作的线程安全方法是使用javax.swing.Timer,而不是java.util.Timer
  • 您正在TimerTask中调用countDown(),并且几乎以递归的方式将新的TimerTask错误地添加到Timer对象。请注意,您甚至不应该使用java.util.TimerTask,因为这是一个Swing应用程序。

解决方案:

  • 改为使用Swing Timer
  • 在Timer的ActionListener中,更新您的秒数,然后设置JLabel的文本。

例如,

// declaration section, create the Swing Timer
private int timerDelay = 1000; // msecs
private Timer myTimer = new Timer(timerDelay, e -> countDown());
// perhaps in a constructor or button's ActionListener, start the Timer
myTimer.start();
private void countDown() {
    // seconds--; // update seconds
    if (minutes == 0 && seconds == 0) {
        myTimer.stop(); // stop the Timer if time's up
        JOptionPane.showMessageDialog(null, "time's up!");
        new Result().setVisible(true);
        this.dispose();
    } else if (seconds == 0) {
        minutes--;
        seconds = 59;
    } else {
        seconds--;
    }

    // create label's text and update JLabel
    String text = String.format("%02d:%02d", minutes, seconds);
    lblTime.setText(text);
}

工作示例:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class TestTimer extends JPanel {
    private static final String FORMAT_TXT = "%02d:%02d";
    private int seconds = 0;
    private int minutes = 10;
    private JLabel lblTime = new JLabel(String.format(FORMAT_TXT, minutes, seconds));
    private int timerDelay = 1000; // msecs
    private Timer myTimer = new Timer(timerDelay, e -> countDown());

    public TestTimer() {
        lblTime.setHorizontalAlignment(SwingConstants.CENTER);
        setLayout(new BorderLayout());
        add(lblTime, BorderLayout.PAGE_START);
        add(new JButton(new AbstractAction("Start") {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (myTimer != null && !myTimer.isRunning()) {
                    myTimer.start();                    
                }
            }
        }));
    }

    private void countDown() {
        if (minutes == 0 && seconds == 0) {
            if (myTimer != null && myTimer.isRunning()) {
                myTimer.stop(); // stop the Timer if time's up
            }
            JOptionPane.showMessageDialog(this, "time's up!");
            // new Result().setVisible(true);
            // this.dispose();
        } else if (seconds == 0) {
            minutes--;
            seconds = 59;
        } else {
            seconds--; // update seconds
        }
        // create label's text and update JLabel
        String text = String.format("%02d:%02d", minutes, seconds);
        lblTime.setText(text);
    }

    private static void createAndShowGui() {
        TestTimer mainPanel = new TestTimer();

        JFrame frame = new JFrame("Test Timer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.