【问题标题】:How to bind inner class controller to FXML?如何将内部类控制器绑定到 FXML?
【发布时间】:2019-11-07 11:09:09
【问题描述】:

我想将内部类“FinishDialogController”控制器绑定到 FXML。 这是一个真正的难题。

但是fx:controller="app.view.MainLayoutController.FinishDialogController" 是错误的。

谁知道正确的方法?

我在Introduction to FXML 中搜索“inner”,但没有找到。

这是完整的 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>

【问题讨论】:

  • 尝试使用 $ 作为分隔符 app.view.MainLayoutController$FinishDialogController
  • @mr mcwolf 感谢您的回复。听起来是个好主意,但它并没有解决我的问题。
  • 你的内班是static吗?非static 内部类不能在没有controllerFactory 的情况下由FXMLLoader 初始化,因为它们的构造函数在参数列表的开头有一个隐藏的附加参数:封闭类的实例。是public吗? FXMLLoader 不会初始化任何非public 类。
  • @fabian 谢谢你的回复,我的问题已经解决了。

标签: java javafx fxml fxmlloader


【解决方案1】:

听起来是个好主意,但它不能解决我的问题。

这是什么意思?究竟是什么问题?

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);
    }
}

运行上面的例子,控制器初始化成功:

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

【讨论】:

  • 谢谢。当我删除“OnActive”语句时,问题解决了。我现在使用 lambda "deleteButton.setOnAction(this::handleDeleteButton)"。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-11
  • 2013-10-26
  • 1970-01-01
  • 2013-03-04
  • 2017-05-10
  • 1970-01-01
  • 2023-03-19
相关资源
最近更新 更多