gpt4 book ai didi

java - 我的 TimerTask 函数无法更新 label.setText

转载 作者:行者123 更新时间:2023-12-01 09:56:44 25 4
gpt4 key购买 nike

我正在编写一个涉及计时器的小程序,但由于某种原因我无法让 TimerTask 来更新 Label.setText 的值

public class Main extends Application  {


Label TimerLabel;
/* Create a Button named button */
Button button;
/* Create three Radiobuttons named Radio1,Radio2,Radio3 */
RadioButton Radio1, Radio2, Radio3;

Timer QuestionTimer = new Timer();
TimerTask QuestionTick = new TimerTask() {
@Override
public void run() {
TimerLabel.setText(String.valueOf(Integer.valueOf(TimerLabel.getText())+1));
}
};

public static void main(String[] args) {
launch(args);
}

/*UI Part*/
@Override
public void start(Stage primaryStage) throws Exception {


/*Window(Stage) Title is set to "Try 1"*/
primaryStage.setTitle("Try 1");

/*Button properties*/
button = new Button();
button.setText("Click Me");


//Radio Button
Radio1 = new RadioButton();
Radio1.setText("Click Me 1");
Radio1.setOnAction(e->{
System.out.println("Radio Button Clicked");
});

Radio2 = new RadioButton();
Radio2.setText("Click Me 2");
Radio2.setOnAction(e->{
System.out.println("Radio Button 2 Clicked");
});

Radio3 = new RadioButton();
Radio3.setText("Click Me 3");
Radio3.setOnAction(e->{
System.out.println("Radio Button 3 Clicked");
});

TimerLabel = new Label();
TimerLabel.setText("0");


/*Here my layout is defined */
Pane Buttonlayout = new Pane();
button.setLayoutX(200);
button.setLayoutY(200);
Radio1.setLayoutX(15);
Radio1.setLayoutY(20);
Radio2.setLayoutX(15);
Radio2.setLayoutY(40);
Radio3.setLayoutX(15);
Radio3.setLayoutY(60);
TimerLabel.setLayoutX(100);
TimerLabel.setLayoutY(20);
Buttonlayout.getChildren().add(button);
Buttonlayout.getChildren().add(Radio1);
Buttonlayout.getChildren().add(Radio2);
Buttonlayout.getChildren().add(Radio3);
Buttonlayout.getChildren().add(TimerLabel);

/*Here we define the scene (aka everything inside the stage (inside the window))*/
Scene scene1 = new Scene(Buttonlayout,300,250);


primaryStage.setScene(scene1);
primaryStage.show();

QuestionTimer.scheduleAtFixedRate(QuestionTick,1000,1000);
}

}

这就是我的代码,我知道其中大部分看起来很愚蠢,但我首先想开始在计时器上编程,但它不起作用。任何形式的帮助将不胜感激

最佳答案

从代码中可以看出您正在使用java.util.Timer类。文档指出实现说明:所有构造函数都会启动一个计时器线程。JavaFX UI 不应从另一个线程更新,而这正是您对计时器所做的事情。

不要直接更新 UI,而是使用 Platform.runLater(Runnable)在主 JavaFX 线程上安排 UI 任务。

javafx.application.Platform.runLater(new Runnable() {
@Override
public void run() {
TimerLabel.setText(String.valueOf(Integer.valueOf(TimerLabel.getText())+1));
}
}

请帮自己一个忙,摆脱方法链。当 Integer.valueOf 抛出 Exception 时,它将使调试变得更容易。

String timer_label = TimerLabel.getText();
Integer timer_int = Integer.valueOf(timer_label);
String timer_text = String.valueOf(timer_int + 1);
TimerLabel.setText(timer_text);

关于java - 我的 TimerTask 函数无法更新 label.setText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37161831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com