JavaFx元素未绑定到fx:id上的控制器变量 [英] JavaFx element not binding to controller variable on fx:id

查看:360
本文介绍了JavaFx元素未绑定到fx:id上的控制器变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是导频错误,但FXML属性未绑定到fx:id上的控制器类。我把它简化为一个微不足道的例子,但仍然没有快乐。我有什么看法?

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文件......

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>

相关的Java代码是......

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不是问题,我我很确定我忽略了一些简单的东西。

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

推荐答案

在构造函数中尚未分配FXML元素,但您可以使用Initializable已经分配了元素的接口。

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

我认为你应该知道你应该使用FXML创建控制器,例如: FXMLLoader.load(getClass()。getResource(sample.fxml);

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

这篇关于JavaFx元素未绑定到fx:id上的控制器变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆