javajavafxfxmlfxmlloader

How to bind inner class controller to FXML?


I want to bind a inner class "FinishDialogController" Controller to FXML. This is a real conundrum.

But fx:controller="app.view.MainLayoutController.FinishDialogController" is wrong .

Who knows the correct way?

I search for "inner" in Introduction to FXML ,but no found.

this is full FXML:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane prefHeight="108.0" prefWidth="350.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="app.view.MainLayoutController.FinishDialogController">
   <children>
      <TextField fx:id="textField" layoutX="25.0" layoutY="50.0" onAction="#handleTextField" prefHeight="23.0" prefWidth="314.0" AnchorPane.leftAnchor="25.0" AnchorPane.rightAnchor="25.0" />
      <Button fx:id="okButton" layoutX="219.0" layoutY="78.0" mnemonicParsing="false" onAction="#handleOkButton" text="OK" />
      <Button fx:id="deleteButton" layoutX="271.0" layoutY="78.0" mnemonicParsing="false" onAction="#handleDeleteButton" text="Delete" />
   </children>
</AnchorPane>


Solution

  • Sounds like a good idea, but it doesn't solve my problem.

    What this means? What exactly is the problem?

    public class Parent {
        public static class Child {
    
            @FXML
            private Label label;
    
            @FXML
            private void initialize() {
                System.out.println("initialize " + getClass().getName());
                System.out.println("label =  " + label);
            }
        }
    }
    

    <AnchorPane xmlns="http://javafx.com/javafx"
                xmlns:fx="http://javafx.com/fxml"
                fx:controller="sample.Parent$Child">
    
        <Label fx:id="label" text="Test"/>
    
    </AnchorPane>
    

    public class Sample extends Application {
    
        public void start(Stage stage) throws Exception {
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(getClass().getResource("/sample/test.fxml"));
    
            Parent root = loader.load();
            Scene scene = new Scene(root, 400, 200);
    
            stage.setScene(scene);
            stage.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    When running the above example, the controller initializes successfully:

    initialize sample.Parent$Child
    label =  Label[id=label, styleClass=label]'Test'