我有一个 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;
}
最佳答案
这是一种方法,只需在秒
字段中输入您想要的秒数即可:
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");
}
}
关于java - Jpanel倒计时1小时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22919261/