gpt4 book ai didi

JavaFx 元素未绑定(bind)到 fx :id 上的 Controller 变量

转载 作者:行者123 更新时间:2023-11-30 07:11:39 35 4
gpt4 key购买 nike

这可能是飞行员错误,但 FXML 属性未绑定(bind)到 fx:id 上的 Controller 类。我已将其缩减为一个微不足道的示例,但仍然“没有乐趣”。我忽略了什么?

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

self 在这里不是问题,我很确定我忽略了一些简单的事情。

最佳答案

FXML 元素尚未在构造函数中分配,但您可以使用已分配元素的 Initialized 接口(interface)。

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 创建 Controller ,例如:FXMLLoader.load(getClass().getResource("sample.fxml");

关于JavaFx 元素未绑定(bind)到 fx :id 上的 Controller 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39134126/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com