How to pass object created in FXML Controller1 to Controller2 of inner FXML control

后端 未结 2 560
时光取名叫无心
时光取名叫无心 2020-11-28 08:26

I have a JavaFX 2.0 application, which consists of two FXML files, and two controllers for them + one "main" .java file.

At the start time, FXML1 is initial

相关标签:
2条回答
  • 2020-11-28 08:44

    In FX 2.2 new API for controller-node was introduced:

    // create class which is both controller and node
    public class InnerFxmlControl extends HBox implements Initializable {
      @FXML public ComboBox cb;
    
      public InnerFxmlControl () {
         FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml_example2.fxml"));
         fxmlLoader.setRoot(this);
         fxmlLoader.setController(this);
         try {
             fxmlLoader.load();            
         } catch (IOException exception) {
             throw new RuntimeException(exception);
         }
      }
    

    with next fxml (note tag fx:root):

    <fx:root type="javafx.scene.layout.HBox" xmlns:fx="http://javafx.com/fxml">
      <children>
        <ComboBox fx:id="cb" />
      </children>
    </fx:root>
    

    By this you've created a new control, which you can use as regular JavaFX controls. E.g. in your case:

    @FXML protected void handleSubmitButtonAction(ActionEvent event) {
        // you just create new control, all fxml tricks are encapsulated
        InnerFxmlControl root = new InnerFxmlControl();
        // and you can access all its' methods and fields including matched by @FXML tag:
        root.cb.getItems().add("new item");
    
        Scene cc = buttonStatusText.getScene();
        cc.setRoot(root);
      }
    

    and in fxml:

    <InnerFxmlControl />
    
    0 讨论(0)
  • 2020-11-28 09:00

    i'm using 1.7.0_21, it can now code like this: in main app fxml file ,

    <VBox ...>
          <fx:include fx:id="tom" source="Tom.fxml" />
    </VBox>
    

    and the included fxml can defind it's own fxml file , like this :

    <AnchorPane id="AnchorPane" fx:id="tomPan" ... xmlns:fx="http://javafx.com/fxml" fx:controller="**com.tom.fx.TomController**">
    

    and then , in the main application contoller require the "Tom.fxml" 's controller like this :

     @FXML private TomController tomController;
    

    notice the "@FXML" . maybe it invoke the contoller automatic.

    0 讨论(0)
提交回复
热议问题