I am not sure what I am doing wrong in the following code. The alert box does not render about 1 in 5 times when I click the "PRESS ME!" for the first time after I run the code. It renders fine every time I click the button after that. To test the code you may have to run this code multiple times. Can someone please go through the code and spot as to why this is happening.
I am using: java version "1.8.0_101" Java(TM) SE Runtime Environment (build 1.8.0_101-b13) Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)
OS: ubuntu 16.04 LTS
Here is the code:
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();
}
}
Thanks for all your suggestions in advance.
Edit:
I have uploaded a video at youtube video which shows the behavior. Please see if you observe the same. In this video I have also removed the Platform.runLater(...) to show that the rendering issue does not go away!