Java JFrame实现60秒倒计时功能,并显示在左上角
下面是一个示例代码,实现了一个60秒钟倒计时功能,并在窗体的左上角显示倒计时时间。倒计时结束时,会在窗体中心显示一条信息,并退出窗口。
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CountdownTimer extends JFrame {
private JLabel countdownLabel;
public CountdownTimer() {
setTitle('倒计时');
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
countdownLabel = new JLabel('', SwingConstants.CENTER);
countdownLabel.setPreferredSize(new Dimension(200, 50));
countdownLabel.setFont(new Font('Arial', Font.BOLD, 24));
countdownLabel.setForeground(Color.RED);
add(countdownLabel);
TimerAction timerAction = new TimerAction();
javax.swing.Timer timer = new javax.swing.Timer(1000, timerAction);
timer.start();
pack();
setVisible(true);
}
private class TimerAction implements ActionListener {
private int count = 60;
@Override
public void actionPerformed(ActionEvent e) {
count--;
countdownLabel.setText(String.valueOf(count));
if (count == 0) {
countdownLabel.setText('倒计时结束');
((javax.swing.Timer) e.getSource()).stop();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
dispose();
}
}
}
public static void main(String[] args) {
new CountdownTimer();
}
}
通过创建一个继承自JFrame的CountdownTimer类,该类包含一个倒计时的JLabel组件。在构造函数中,设置了窗体的标题、关闭操作、布局、位置等属性。倒计时的逻辑在TimerAction类中实现,通过javax.swing.Timer每隔1秒钟执行一次操作,更新倒计时时间并判断是否倒计时结束。倒计时结束后,显示一条信息,并调用dispose()方法关闭窗口。最后,在main方法中创建一个CountdownTimer对象来启动倒计时窗口。
原文地址: https://www.cveoy.top/t/topic/vUy 著作权归作者所有。请勿转载和采集!