我不确定我在下面的代码中做错了什么。当我单击"PRESS ME!“时,警告框不会呈现大约1/5次。在我运行代码之后的第一次。在那之后,我每次点击按钮,它都会渲染得很好。要测试代码,您可能需要多次运行此代码。有没有人可以浏览一下代码,看看为什么会发生这种情况。
我使用的是: java版本"1.8.0_101“Java(TM) SE运行时环境(build 1.8.0_101-b13) Java HotSpot(TM) 64位服务器VM (build 25.101-b13,混合模式)
操作系统: ubuntu 16.04 LTS
代码如下:
package javaapplication;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class JavaApplication extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Font font = new Font(40);
Text helloWorldText1 = new Text("Hello World from ");
Text helloWorldText2 = new Text("JavaFX!!");
helloWorldText1.setFont(font);
helloWorldText2.setFont(font);
helloWorldText2.setFill(Color.RED);
HBox hBox1 = new HBox(helloWorldText1, helloWorldText2);
HBox hBox2 = new HBox(20);
Button okButton = new Button("PRESS ME!");
okButton.setOnAction(e -> {
Platform.runLater(() -> {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setContentText("You pressed OK!");
alert.showAndWait();
});
});
Button cancelButton = new Button("CANCEL!!");
cancelButton.setOnAction(e -> System.exit(0));
hBox2.getChildren().addAll(okButton, cancelButton);
hBox2.setAlignment(Pos.BOTTOM_RIGHT);
VBox vBox = new VBox(10);
vBox.getChildren().addAll(hBox1, hBox2);
vBox.setAlignment(Pos.CENTER);
vBox.setPadding(new Insets(20));
primaryStage.setScene(new Scene(vBox));
primaryStage.show();
}
}感谢您事先提出的所有建议。
编辑:
我已经在youtube video上传了一段视频,展示了这种行为。请看你是否遵守了同样的规定。在此视频中,我还删除了Platform.runLater(...)以显示渲染问题不会消失!
发布于 2016-08-11 04:00:08
Iv在两个窗口,manjaro linux和lubuntu上测试了应用程序,但没有ubuntu本身,iv没有issue...that,说有时我在linux和javafx上遇到奇怪的问题,特别是在图形方面,比如全屏视图等。
然而,由于我无法在目前为止尝试过的任何操作系统上重现该问题,因此请猜测一下:
方法Platform.runLater(java.lang.Runnable runnable)在将来某个未指定的时间在JavaFX应用程序线程上运行指定的Runnable。
因此,没有理由需要延迟窗口的出现,比如在窗口加载的同时在后台加载一些东西,然后可能只需要尝试这个事件:
okButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setContentText("You pressed OK!");
alert.showAndWait();
}
});为了提供更多信息,还有另一篇文章here详细描述了发生的事情,但无论如何我都会在这里引用:
请记住,按钮的onAction是在JavaFX线程上调用的,因此您实际上是将UI线程暂停了5秒钟。
如果您确实需要在Javafx线程上调用事件,它们还提供了一种变通方法。希望这对你的项目有所帮助,并祝你好运!
发布于 2016-08-14 03:26:56
我运行你的program.Your程序没有任何问题。您的计算机是造成延迟的原因。
https://stackoverflow.com/questions/38881266
复制相似问题