我正在创建一个对话框,并在控制器Platform.runLater()
方法中调用initialize()
。
当我尝试使用showAndWait()
打开对话框时,它会加载FXML (我知道这样做是因为警告是在Running Later
和After first showAndWait
)之前打印的但是没有&# 39;打开对话框。只有第二次拨打showAndWait()
即可打开它。有这种有线行为的原因还是这个错误?
控制台输出是:
Starting dialog creation
Running Later
After first showAndWait
Closing
After second showAndWait
但应该是:
Starting dialog creation
Init
Running Later
Closing
After first showAndWait
Closing
After second showAndWait
还有这个警告:
Apr 20, 2018 12:20:32 AM javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 9.0.1 by JavaFX runtime of version 8.0.161
但据我所知,这只意味着我的JavaFX版本已经过时了。
主要课程:
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class Main extends Application{
public static void main(String[] args) {
launch();
}
@Override
public void start(Stage stage) throws Exception {
stage.setScene(new Scene(new BorderPane()));
stage.show();
System.out.println("Starting dialog creation");
Dialog<Optional<List<String>>> popup = new Dialog<>();
FXMLLoader loader = new FXMLLoader(Main.class.getClassLoader().getResource("Dialog.fxml"));
try {
popup.setDialogPane(loader.load());
} catch (IOException e) {
e.printStackTrace();
}
Controller controller = loader.getController();
controller.dialog = popup;
popup.getDialogPane().getButtonTypes().add(ButtonType.CLOSE);
popup.showAndWait();
System.out.println("After first showAndWait");
popup.showAndWait();
System.out.println("After second showAndWait");
}
}
控制器:
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.scene.control.Dialog;
public class Controller {
@FXML
private ResourceBundle resources;
@FXML
private URL location;
public Dialog<Optional<List<String>>> dialog;
@FXML
void initialize() {
System.out.println("Init");
Platform.runLater(() -> {
System.out.println("Running Later");
dialog.setResult(Optional.empty());
dialog.setOnCloseRequest(e -> {
System.out.println("Closing");
});
});
}
}
FXML:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.DialogPane?>
<DialogPane contentText="This is a text" headerText="Test" xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Controller" />