I have a thread that is running every 5 seconds inside my child stage. When I open and close child stage, this thread is kept on running. It should remove all the child's stage events and contents on close button click (cross at top right of screen). I am printing text on basis of TEXT inside child stage.
It prints as
NOT NULL
which means node is still present on the screen. It will affect app performance as I need to open and close these child stages frequently. Please advice, here is my code.
Main class:
public class dashboard extends Application {
@Override
public void start(Stage primaryStage) {
BorderPane pane = new BorderPane();
Button btn = new Button("Open child window");
btn.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
final Stage dialog = new Stage();
dialog.setTitle("Sensors Assignment");
dialog.initModality(Modality.WINDOW_MODAL);
dialog.initOwner(primaryStage);
dialog.setResizable(false);
VBox dialogVbox = (new childWindowClass()).GetChildContent();
//dialogVbox.getChildren().add(closeButton);
Scene dialogScene = new Scene(dialogVbox);
dialog.setScene(dialogScene);
dialog.showAndWait();
dialog.setOnCloseRequest(e -> {System.out.println("Stage is closing");dialog.close();});
}
});
pane.setCenter(new VBox(new Text("Test 1234"), btn));
ScrollPane scrollPane = new ScrollPane(pane);
scrollPane.setFitToWidth(true);
scrollPane.setHbarPolicy(ScrollBarPolicy.NEVER);
scrollPane.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);
Scene scene = new Scene(scrollPane);
primaryStage.setTitle("test");
primaryStage.setMaximized(true);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Child class:
public class childWindowClass {
private Text txt; private int _index = 0; SimpleDateFormat dateFrmt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
public VBox GetChildContent() {
txt = new Text("Child Window Test " + _index);
Label refreshClock = new Label(dateFrmt.format(new Date()));
Thread timerThread = new Thread(() -> {
while (true) {
try { Thread.sleep(5000); }
catch (InterruptedException e) {e.printStackTrace();}
Platform.runLater(() -> {
refreshClock.setText(dateFrmt.format(new Date()));
try {
System.out.println(dateFrmt.format(new Date()) + " - " + (txt == null ? "" : " not") + " NULL");
if(txt != null)
txt.setText("Child Window Test " + _index);
_index++;
}
catch (Exception e) {e.printStackTrace();}
});
}
});
timerThread.start();
return new VBox(txt, refreshClock);
}
}