我在学习 javaFX 我的问题是我有一些带有选择框和按钮的简单窗口。这个窗口是通过 FXML 定义的,它也与 Controller 类相关联。
我想知道,如何用 Controller 类中的数据填充这个选择框,因为使用@FXML 引用这个选择框会抛出 NullpointerEception
编辑 - 添加源代码
FXML 代码
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="240.0"
prefWidth="320.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
fx:controller="supermarket.ManageWindowCC">
<children>
<ChoiceBox fx:id="countChoiceBox" layoutX="44.0" layoutY="71.0" prefHeight="25.0" prefWidth="191.0"/>
<Label layoutX="44.0" layoutY="54.0" text="To change item's count, choose one"/>
<TextField layoutX="140.0" layoutY="129.0" prefHeight="25.0" prefWidth="24.0"/>
<Label layoutX="123.0" layoutY="112.0" text="New count"/>
<Button layoutX="126.1875" layoutY="171.5" mnemonicParsing="false" text="Submit"/>
</children>
Java Controller 代码:
public class ManageWindowCC {
@FXML
private ChoiceBox countChoiceBox;
public void onChangeCountClick(ActionEvent actionEvent) {
try {
Parent root = FXMLLoader.load(getClass().getResource("ChangeCount.fxml"));
Stage newStage = new Stage();
newStage.setTitle("Change item's count");
newStage.setScene(new Scene(root, 320, 240));
newStage.show();
countChoiceBox = new ChoiceBox();
countChoiceBox.setItems(FXCollections.observableArrayList("One","Two","Three"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
感谢您的帮助和时间
最佳答案
如何修复它
删除行 countChoiceBox = new ChoiceBox();
假设您的应用程序的其他地方没有其他错误,一切都会正常进行。
该程序将使用对 countChoiceBox 的引用,它是由 FXMLLoader 创建并在您的场景中设置的节点层次结构的一部分。
发生了什么
在 onChangeCountClick
中加载新的 FXML将要:
supermarket.ManageWindowCC
Controller 。 因此,在加载 FXML 后,countChoiceBox 被初始化为由 FXMLLoader 实例化的空 ChoiceBox
到目前为止,这一切都很好。 . .
然后你要做的是(错误地)写:
countChoiceBox = new ChoiceBox();
您违反的经验法则是 => 永远不要使用
new
创建一个赋值给标记为 @FXML
的成员.另请参阅 populating a ComboBox using FXML 的相关示例(尽管该示例使用 ComboBox 并直接在 FXML 中填充其数据,因此它不直接适用于您的情况)。
关于javafx - 填充 FXML 中定义的选择框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23067256/