Jpanel倒计时1小时?

时间:2014-04-07 17:33:24

标签: java swing countdown countdowntimer

我有一个计时器的Jpanel,我希望在其中有一个倒数计时器1小时。

我真的不知道怎么做?我有一个计时器代码实现但我想从头开始编写,任何人都有模板吗?

我只是不能让它出现,我可以使静态文本看起来像“定时器到这里”,但倒计时对我来说似乎是不可能的。真的很感激帮助。谢谢!

private JPanel timer() {
    JPanel timerPanel = new JPanel();
    timerPanel.setMinimumSize(new Dimension(100, 100));
    timerPanel.setPreferredSize(new Dimension(100, 100));

    Countdown(timer, timer);
    JLabel timerLabel = new JLabel("TIMER GOES HERE");
    timerLabel.setFont(new Font("Franklin Gothic Medium", Font.PLAIN, 18));
    timerLabel.setAlignmentX(0);
    timerPanel.add(timerLabel);
    timerPanel.add(Box.createRigidArea(new Dimension(10, 10)));

    return timerPanel;
}

2 个答案:

答案 0 :(得分:5)

这是一种方法,只需在seconds字段中输入您想要的秒数:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.TimeUnit;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

public class CountdownTimer {
    static int seconds = 100000;

    public static void main(String[] args) {
        JFrame frame = new JFrame("Countdown");
        JPanel panel = new JPanel();
        final JLabel label = new JLabel();
        panel.add(label);
        frame.add(panel);
        frame.setSize(500, 500);
        frame.setVisible(true);
        Timer timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                seconds--;
                int day = (int) TimeUnit.SECONDS.toDays(seconds);
                long hours = TimeUnit.SECONDS.toHours(seconds) - (day * 24);
                long minute = TimeUnit.SECONDS.toMinutes(seconds)
                        - (TimeUnit.SECONDS.toHours(seconds) * 60);
                long second = TimeUnit.SECONDS.toSeconds(seconds)
                        - (TimeUnit.SECONDS.toMinutes(seconds) * 60);
                label.setText(hours + " Hour(s), " + minute + " Minute(s) and "
                        + second + " Second(s)");
                if (seconds == 0) {
                    doSomething();
                }
            }
        });
        timer.start();
    }

    public static void doSomething() {
        System.out.println("Something");
    }
}

答案 1 :(得分:0)

您不需要像计时器那样实现基本功能,javax.swing.Timer就是这样。只需初始化其中一个延迟1秒,更新标签的值,重新绘制面板。