加载空窗口javafx

时间:2018-04-21 09:47:17

标签: java javafx netbeans scenebuilder

当我运行此代码时,它应该打开一个加载了fxml的新窗口,但它只是打开一个空的窗口。

启动代码:

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时,它不显示错误,只是没有加载新屏幕。

1 个答案:

答案 0 :(得分:0)

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>