首页 > 解决方案 > JAVA 和 JAVAFX 问题 - 尝试将附加控制器连接到主控制器

问题描述

大家下午好。我通常会尝试自己查找和修复错误,但这次我真的被卡住了。我的任务是写一个贷款计算器。所有代码都可以正常工作和编译,直到我需要创建一个折线图/图表,它会在一个新窗口中弹出。
问题在于加载 FXML 文件或将附加控制器连接到主控制器。
我尝试了不同的方法并在不同的论坛中检查了解决方案,但无法在我的代码中实现一个。谁能给我一个解决方案?

这是我的 Main 启动程序。

public class Main extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("Scene.fxml"));
        primaryStage.setTitle("Loan calculator");
        primaryStage.setScene(new Scene(root, 770, 410));
        primaryStage.setResizable(false);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

这是我的主控制器。小笔记。我了解我在主控制器中使用第二个控制器的“初始化”方法的方式不正确,但我尝试了不同的方法,但它们并没有给我更好的结果

public class Controller implements Initializable {
    public static int years = 0;
    public static int months = 0;
    private double desiredLoan = 1; //should be set to zero,but for testing is set differently

    private boolean graph = true; //true - linear, false - annuity

    @FXML
    private Button Button_3 = new Button();

    private LineGraphController lineGraphController = new LineGraphController("Linear");
    private AnnuityGraphController annuityGraphController = new AnnuityGraphController("Annuity");


/**Some code to count my data*/

    @Override /** This method is used to access my UI elements and access other controllers*/
    public void initialize(URL url, ResourceBundle resourceBundle) {
        Button_3.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                try {
                    if (desiredLoan == 0 && months == 0 && years == 0) {
                        throw new RuntimeException();
                    }
                    else {
                        if (whatGraph() == true) { //make linear graph
                            lineGraphController.initialize(url, resourceBundle);
                        }
                        else {//make annuity graph
                            annuityGraphController.initialize(url, resourceBundle);
                        }
                    }
                }
                catch (RuntimeException error) {
                    error.printStackTrace();
                }
            }
        });
    }

    /** Getters and setters */
    public boolean whatGraph() {
        return graph;
    }
    public void setGraph(boolean graph) {
        this.graph = graph;
    }
}

我的主要控制器:
折线图控制器

/** This controller is used to load additional fxml file*/
public class LineGraphController implements Initializable {
    @FXML
    public LineChart<?, ?> LineGraph;
    private String title;

    public LineGraphController(String title) {
        this.title = title;
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("LineGraph.fxml"));
        Parent lineGraph = null;
        try {
            lineGraph = (Parent)fxmlLoader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Stage window = new Stage();
        window.initModality(Modality.APPLICATION_MODAL);
        window.setTitle(title);
        window.setResizable(false);
        window.setMinWidth(600);
        window.setMinHeight(400);
        window.setScene(new Scene(lineGraph));
        window.showAndWait();
    }
}

年金图控制器

/** This controller is used to load additional fxml file*/
public class AnnuityGraphController implements Initializable {
    @FXML
    public LineChart<?, ?> AnnuityGraph;
    private String title;

    public AnnuityGraphController(String title) {
        this.title = title;
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("AnnuityGraph.fxml"));
        Parent lineGraph = null;
        try {
            lineGraph = (Parent)fxmlLoader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Stage window = new Stage();
        window.initModality(Modality.APPLICATION_MODAL);
        window.setTitle(title);
        window.setResizable(false);
        window.setMinWidth(600);
        window.setMinHeight(400);
        window.setScene(new Scene(lineGraph));
        window.showAndWait();
    }
}

我的主要 FXML 文件。

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" style="-fx-background-color: #4a4a4a;" xmlns="http://javafx.com/javafx/10.0.2" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Paskolu_Skaiciuokle.Controller">
   <center>
      <Button fx:id="Button_3" maxWidth="150.0" mnemonicParsing="false" prefHeight="26.0" prefWidth="100.0" style="-fx-effect: dropshadow(gaussian, rgba(0, 0, 0, 0.3), 3, 0,5, 5, 5);" text="Show graph" BorderPane.alignment="CENTER">
         <font>
            <Font name="Times New Roman" size="12.0" />
         </font>
      </Button>
   </center>
</BorderPane>

我的控制器附加 FXML 文件:
折线图 FXML

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="670.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/10.0.2" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Loan_calculator.LineGraphController">
 <!-- some code -->
</AnchorPane>

年金图 FXML

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="670.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/10.0.2" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Loan_calculator.AnnuityGraphController">
 <-- some code -->
</AnchorPane>

提前感谢您的帮助。
ps 这些是我试图寻找解决方案的链接,有很多不同的编码方法,但是找不到我可以在我的代码中实现的方法..或者我只是缺乏如何实现的知识做。无论哪种方式,我希望有人能够帮助我或解释如何解决这个问题。链接:
•<a href="https://stackoverflow.com/questions/14187963/passing-parameters-javafx-fxml?fbclid=IwAR1ICwbk_Vjt8apw_r4f7X6m3_Y7MbuJnqVhEckQemO4XfPyVs6Wjz0rtDM">传递参数JavaFX FXML
•<a href="https://stackoverflow.com /questions/19342259/how-to-create-multiple-javafx-controllers-with-different-fxml-files?fbclid=IwAR0vTzxmyZVOjHfpXGbFcR1MaX9GynTUnzYdCfD88d95K2QkInDF1neT4M8">
•<a href="https://stackoverflow.com/questions/12166786/multiple-fxml-with-controllers-share-object/?fbclid=IwAR3olxpF8y1SKEjfyDUCOWcb7Bw5pnS4QVN4UCaFMtAZiAlfAKL11JvtFew">带控制器的多个 FXML,共享对象
我的主要问题是访问其他控制器从我的主控制器。(所有控制器都链接到它们自己的 FXML 文件)。

标签: javajavafxcontrollerfxmlfxmlloader

解决方案


我不太了解您的问题,但我尝试回答。我认为您想从主控制器访问其他控制器,最简单的方法是:

FXMLLoader mainLoader = new FXMLLoader(getClass().getResource("MainController.fxml"));
Parent main = mainLoader.load();
MainController mainController = mainLoader.getController();

FXMLLoader otherLoader = new FXMLLoader(getClass().getResource("OtherController.fxml"));
Parent other = otherLoader.load();
// set other controller in main controller
mainController.setOtherController(otherLoader.getController());

如果你使用javafx-weaver和 spring boot,DI 会更容易:

@Component
@FxmlView
class MainController {
    @Autowired
    private FxControllerAndView<OtherController, VBox> otherControllerAndView;

    // otherControllerAndView.getController() to access other controller
}

推荐阅读