+-

我的目标是在舞台场景出现后每秒查看矩形的颜色变化.
我研究并尝试了几件事:
> primaryStage.show()下的代码[看我的示例代码]
> primaryStage.setOnShown()或primaryStage.setOnShowing()
>舞台上的EventHandler
>来自场景的EventHandler
>带事件处理程序的按钮
一切都是徒劳.
在大多数情况下,阶段就会来到,然后程序在后台执行颜色更改(没有可视化),最后场景以最终结果出现.还是版本2:我什么也没看到,代码会通过,最后立即得到最终结果.
这是我的代码:
package sample;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
GridPane gridPane = new GridPane();
Rectangle[] recs = new Rectangle[10];
for (int i = 0; i < recs.length; i++) {
recs[i] = new Rectangle(30, 30, Color.GREEN);
recs[i].setStroke(Color.BLACK);
gridPane.add(recs[i], i, 0);
}
primaryStage.setTitle("Code after primaryStage.show()");
primaryStage.setScene(new Scene(gridPane, 400, 300));
primaryStage.show();
for (Rectangle rec : recs) {
Thread.sleep(1000);
rec.setFill(Color.ORANGE);
}
}
public static void main(String[] args) {
launch(args);
}
}
最佳答案
这里的问题是您的循环正在主应用程序线程上运行,因此它将锁定任何GUI更新,直到完成为止.
而是在自己的线程上执行循环,并使用Platform.runLater()更新每个矩形:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
GridPane gridPane = new GridPane();
Rectangle[] recs = new Rectangle[10];
for (int i = 0; i < recs.length; i++) {
recs[i] = new Rectangle(30, 30, Color.GREEN);
recs[i].setStroke(Color.BLACK);
gridPane.add(recs[i], i, 0);
}
primaryStage.setTitle("Code after primaryStage.show()");
primaryStage.setScene(new Scene(gridPane, 400, 300));
primaryStage.show();
new Thread(() -> {
for (Rectangle rec :
recs) {
try {
Thread.sleep(1000);
Platform.runLater(() -> rec.setFill(Color.ORANGE));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
public static void main(String[] args) {
launch(args);
}
}
那么发生了什么?
new Thread(() -> {
在应用程序的后台打开一个新线程,以便UI保持响应.
然后,我们可以在try / catch块中开始循环.
Platform.runLater(() -> rec.setFill(Color.ORANGE));
使用后台线程时,重要的是要知道您不能直接对UI进行更改.该行告诉JavaFX在JavaFX Application线程上执行rec.setFill()语句.
.start();
您已经创建了新线程,这将启动它.
点击查看更多相关文章
转载注明原文:JavaFX,primaryStage.show()之后的代码如何? - 乐贴网