在下面的代码中, Pane 的背景颜色将仅在输入之后改变,而不是之前。我不明白为什么:据我所知,程序应该仅在 sc.next();
行之后开始等待输入。有什么办法可以强制改变背景吗?在等待输入之前执行它?
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.Scanner;
public class NewMain extends Application {
@Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
primaryStage.setScene(new Scene(pane, 300, 300));
primaryStage.show();
pane.setBackground(new Background(new BackgroundFill(Color.BLACK, CornerRadii.EMPTY, Insets.EMPTY)));
Scanner sc = new Scanner(System.in);
String str = sc.next();
System.out.println(str);
}
public static void main(String[] args) {
launch(args);
}
}
最佳答案
对 sc.next()
的调用将阻塞,直到用户提供输入。由于 start()
方法是在 FX 应用程序线程(用于渲染 UI 的线程)上执行的,因此在释放该 block 之前,UI 的渲染不会发生。
无论如何,确实不清楚为什么要从 GUI 应用程序中的标准输入读取; GUI 应用程序的全部要点是为用户提供输入控件(文本字段、按钮等)。
如果您出于某种原因确实想从标准输入中读取数据,则需要在后台线程中执行此操作:
public void start(Stage primaryStage) {
Pane pane = new Pane();
primaryStage.setScene(new Scene(pane, 300, 300));
primaryStage.show();
pane.setBackground(new Background(new BackgroundFill(Color.BLACK, CornerRadii.EMPTY, Insets.EMPTY)));
Thread thread = new Thread(() -> {
Scanner sc = new Scanner(System.in);
String str = sc.next();
System.out.println(str);
});
thread.start();
}
请注意,您无法从后台线程更新 UI,因此如果您想使用 UI 中的输入,则需要进一步的代码来使 UI 更改发生在 FX 应用程序线程上。
关于java - 如何立即更换背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48036380/