这是我第一次在很长一段时间内被代码困惑。我需要为一个赋值设置GUI倒计时器,它只是一个输入字段,在点击输入时,它会按你输入的数字倒数秒。我需要它来显示每一秒钟。我知道有一些类我可以用来创建一个计时器但是我们没有在本课程中涵盖任何类似的东西但我想在不使用它们的情况下这样做。我现在的代码只是从输入的数字倒计时然后显示0而不显示倒计时。我在控制台应用程序中使用了类似的逻辑,并且计算得很好,所以我只是尝试将它集成到这个GUI应用程序中。我知道我所拥有的是草率的,可以做得更好,但我只是在寻找能让它发挥作用的技巧。
先谢谢了。 这是我的代码:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class Countdown extends Application {
//create border pane
BorderPane pane = new BorderPane();
//create textfield for timer
TextField text = new TextField();
//variable for input
int inTime;
//start time
double start;
//check time
double checkTime;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage ps) throws Exception {
//add textfield to pane
pane.setCenter(text);
//make a scene
Scene scene = new Scene(pane, 200, 100);
//key press event
text.setOnKeyPressed(e->{
//single out the enter key
if(e.getCode().equals(KeyCode.ENTER)){
//save start time to variable
long start = System.currentTimeMillis();
//variable to allow repeat of while loop
boolean repeat = true;
//set variable to user entry
inTime = Integer.parseInt(text.getText());
//while loop to keep track of seconds
while(repeat) {
//while time being displayed is not at zero
if(inTime != 0){
//repeating function to check if a second has passed
if(System.currentTimeMillis() - start == 1000) {
text.setText("");//clear text in box
text.setText(Integer.toString(inTime));//display current countdown time
inTime -= 1;//decrement the counter
start = System.currentTimeMillis(); //reset start time
}
}
//when count has reached zero
else{
repeat = false;//stop the while loop
text.setText("0");//display zero
}
}
}
});
//put together stage
ps.setScene(scene);
ps.setTitle("BJO Chapter 16 Exercise 21");
ps.show();
}
}