在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庫選擇其中一種方式進行實現。