JavaFx fx:id导致错误 [英] JavaFx fx:id causes error
问题描述
由于某种原因,我的fx:id无法正确绑定到我的Controller
类,因此始终会导致错误.
For some reason, my fx:id does not bind properly to my Controller
class, and thus always causes an error.
控制器
package sample;
import javafx.fxml.FXML;
import java.awt.*;
import java.awt.event.ActionEvent;
public class Controller {
@FXML public Button button;
public void clickAction(ActionEvent actionEvent) {
System.out.println("Button clicked.");
}
}
FXML
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<BorderPane fx:controller="sample.Controller" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<Button text="Click me!" fx:id="button" onAction="#clickAction" BorderPane.alignment="CENTER"/>
</BorderPane>
我认为我了解问题的根源,但我不知道如何正确解决该问题.根据这个问题的答案,我认为我我试图在调用构造函数之前分配FXML元素(这些元素只能在初始化期间/之后分配).
I think I understand the source of my problem, but I do not understand how to properly address it. According an answer of this question, I think I am trying to assign FXML elements before the constructor is called (and these elements can only be assigned during/after initialisation).
有没有一种方法可以在不实现Initializable
的情况下实现 ?还是我犯了一个完全不同的错误?
Is there a way to do this without implementing Initializable
? Or am I making a completely different mistake?
推荐答案
您使用导入
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
在您的fxml文件中.
in your fxml file.
因此,在加载fxml文件时创建的Button
实例是javafx.scene.control.Button
.
Therefore the Button
instance created while loading the fxml file is a javafx.scene.control.Button
.
要注入的字段类型需要为javafx.scene.control.Button
可以分配给的字段.
The type of the field this is injected to needs be something a javafx.scene.control.Button
can be assigned to.
由于除了javafx.fxml.FXML
之外,您在控制器中唯一的导入都是来自java.awt
包,因此button
字段(类型java.awt.Button
)显然不是这种情况.
Since your only imports in the controller besides javafx.fxml.FXML
are from the java.awt
packages, this is clearly not the case for the button
field (type java.awt.Button
).
修复您的控制器,以从javafx
软件包中导入所需的类:
Fix your controller to import the required classes from the javafx
packages instead:
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
BTW:如果您不使用onAction
处理程序的参数,也可以不使用它:
BTW: You can also leave out the parameter of the onAction
handler, if you do not use it:
public void clickAction() {
System.out.println("Button clicked.");
}
这篇关于JavaFx fx:id导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!