在Java图形界面中实现倒计时效果,可以使用Swing或JavaFX库来创建界面和计时器。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CountdownTimer extends JFrame {
private JLabel countdownLabel;
private Timer timer;
private int countdown;
public CountdownTimer(int countdown) {
this.countdown = countdown;
countdownLabel = new JLabel(String.valueOf(countdown), SwingConstants.CENTER);
countdownLabel.setFont(new Font("Arial", Font.BOLD, 48));
timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
countdown--;
countdownLabel.setText(String.valueOf(countdown));
if (countdown <= 0) {
timer.stop();
JOptionPane.showMessageDialog(null, "倒计时结束!");
}
}
});
add(countdownLabel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setVisible(true);
timer.start();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new CountdownTimer(10);
}
});
}
}
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;
public class CountdownTimer extends Application {
private Label countdownLabel;
private Timeline timeline;
private int countdown;
@Override
public void start(Stage primaryStage) {
countdown = 10;
countdownLabel = new Label(String.valueOf(countdown));
countdownLabel.setStyle("-fx-font-size: 48px");
EventHandler<ActionEvent> eventHandler = e -> {
countdown--;
countdownLabel.setText(String.valueOf(countdown));
if (countdown <= 0) {
timeline.stop();
primaryStage.close();
System.out.println("倒计时结束!");
}
};
timeline = new Timeline(new KeyFrame(Duration.seconds(1), eventHandler));
timeline.setCycleCount(countdown);
StackPane root = new StackPane();
root.getChildren().add(countdownLabel);
Scene scene = new Scene(root, 300, 200);
primaryStage.setTitle("倒计时");
primaryStage.setScene(scene);
primaryStage.show();
timeline.play();
}
public static void main(String[] args) {
launch(args);
}
}
以上是两种常用的在Java图形界面中实现倒计时效果的方法,根据具体需求和使用的GUI库选择其中一种方式进行实现。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: java接口和抽象类怎么使用