了JavaFx元件不结合控制器上FX变量:ID [复制](JavaFx element not bi

2019-09-28 01:17发布

这个问题已经在这里有一个答案:

  • JavaFX的FXML控制器-构造VS初始化方法 3个回答

这可能是飞行员操作失误,但FXML属性不结合于FX控制器类:身份证。 我已经缩短到一个简单的例子,但仍然“不快乐”。 我是什么俯瞰?

FXML文件...

<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>

<BorderPane fx:id="mainFrame" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.controller.BorderPaneCtrl">
  <left>
    <AnchorPane fx:id="anchorPaneLeft" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
  </left>
</BorderPane>

相关的Java代码是...

package sample.controller;

import javafx.fxml.FXML;
import javafx.scene.layout.AnchorPane;

public class BorderPaneCtrl {
    @FXML private AnchorPane anchorPaneLeft;

    public BorderPaneCtrl() {
        /* so, @FXML-annotated variables are accessible, but not
         *   yet populated
         */
        if (anchorPaneLeft == null) {
            System.out.println("anchorPaneLeft is null");
        }
    }

/* this is what was missing...added for "completeness"
 */
@FXML
public void initialize() {
    /* anchorPaneLeft has now been populated, so it's now
     *   usable
     */
    if (anchorPaneLeft != null) {
        // do cool stuff
    }
}

自我是不是一个问题在这里,我敢肯定,我俯瞰简单的东西。

Answer 1:

FXML元素在constuctor尚未分配,但可以使用Initializable界面,元素已分配。

public class Controller implements Initializable {
    @FXML
    AnchorPane anchorPaneLeft;

    public Controller() {
        System.out.println(anchorPaneLeft); //null
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        System.out.println(anchorPaneLeft); //AnchorPane
    }
}

我假设你知道你应该使用例如创建FXML控制器: FXMLLoader.load(getClass().getResource("sample.fxml");



文章来源: JavaFx element not binding to controller variable on fx:id [duplicate]