JavaFx element not binding to controller variable on fx:id [duplicate]

不羁的心 提交于 2020-01-06 03:37:26

问题


This is likely pilot error, but the FXML attribute is not binding to the controller class on fx:id. I've whittled it down to a trivial example, but still "no joy". What am I overlooking?

FXML file...

<?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>

The associated Java code is...

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

Ego is not an issue here, I'm pretty sure I'm overlooking something simple.


回答1:


FXML elements are not assigned yet in constuctor, but you can use Initializable interface where elements are already assigned.

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

I assume that you know that you should create controllers with FXML by using for example: FXMLLoader.load(getClass().getResource("sample.fxml");



来源:https://stackoverflow.com/questions/39134126/javafx-element-not-binding-to-controller-variable-on-fxid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!