加载空 window javafx

loading empty window javafx

当我 运行 这段代码应该打开一个新的 window 并加载 fxml 但它只是打开一个空的 window。

启动代码:

public class StartUpGui extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
    DomeinController dc = new DomeinController();
    UC1Controller root = new UC1Controller(dc);
    Scene scene = new Scene(root);
    primaryStage.setTitle("Mastermind");
    primaryStage.setScene(scene);
    primaryStage.show();

}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    launch(args);
}}

第一个屏幕的代码(有效)

public class UC1Controller extends AnchorPane {
 public UC1Controller(DomeinController dc) {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("UC1.fxml"));
    loader.setRoot(this);
    loader.setController(this);
    this.dc = dc;

    try {
        loader.load();
    } catch (IOException ex) {
        Logger.getLogger(UC1Controller.class.getName()).log(Level.SEVERE, null, ex);
    }

@FXML
private void startAnderUC(ActionEvent event) {
    if (event.getTarget() == btn_UC2) {
        startUsecase2();
    }

}


public void startUsecase2() {


    UC2Controller UC2 = new UC2Controller(dc);
    Scene scene = new Scene(UC2);
    Stage stage = new  Stage();
    stage.setTitle("Mastermind");
    stage.setScene(scene);
    stage.show();

}
}

第二个屏幕代码(不起作用)

public class UC2Controller extends AnchorPane {

public UC2Controller(DomeinController dc) {

    FXMLLoader loader = new FXMLLoader(getClass().getResource("UC2.fxml"));
    loader.setController(this);
    this.dc =dc;

    try {
        loader.load();



    } catch (IOException ex) {
        Logger.getLogger(UC1Controller.class.getName()).log(Level.SEVERE, null, ex);
    }

}

}

因此,当我加载第一个时,它会正常运行,但是当我单击按钮启动 useCase2 时,它不会显示错误,只是不会加载新屏幕。

UC2Controller 中,您只需删除加载的结果而不将其添加到场景中。 FXMLLoader 也不添加它,因为您在加载 fxml 之前没有设置 root

您需要在UC2Controller中设置根:

public UC2Controller(DomeinController dc) {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("UC2.fxml"));
    loader.setController(this);
    loader.setRoot(this);
    this.dc = dc;
    try {
        loader.load();
    } catch (IOException ex) {
        throw new RuntimeException(ex); // cannot recover from this -> rethrow exception
    }

}

或者您可以手动将加载的节点添加到场景中:

public UC2Controller(DomeinController dc) {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("UC2.fxml"));
    loader.setController(this);
    this.dc = dc;
    try {
        this.getChildren().add(loader.load());
    } catch (IOException ex) {
        throw new RuntimeException(ex); // cannot recover from this -> rethrow exception
    }

}

第一个选择要求 <fx:root>UC2.fxml 的根元素:

<fx:root xmlns:fx="http://javafx.com/fxml/1" type="javafx.scene.layout.AnchorPane">
    ...
</fx:root>