[英]NullPointerException when attempting to use .setText on a Text object
Whenever I try to use .setText on the Text field in my controller class, I get a NullPointerException. 每当我尝试在控制器类的Text字段上使用.setText时,都会收到NullPointerException。 Here is my controller class:
这是我的控制器类:
public class ViewTripController{
private static File open;
private static Trip trip;
@FXML
static Text budget;
@FXML
static Text spent;
@FXML
void toEditTrip(){
VistaNavigator.loadVista(VistaNavigator.EDIT_TRIP);
}
@FXML
void toAddExpense(){
VistaNavigator.loadVista(VistaNavigator.EDIT_TRIP);
}
public static void setTrip(Trip trip2){
trip = trip2;
}
public static void budgetText(String text){
budget.setText(text);
}
public static void spentText(String text){
spent.setText(text);
}
public static void setFile(File file){
open = file;
}
}
Here is my FXML file: 这是我的FXML文件:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>
<StackPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javafx.ViewTripController">
<children>
<Pane prefHeight="400.0" prefWidth="600.0">
<children>
<Text layoutX="68.0" layoutY="87.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Total Budget: " />
<Text layoutX="68.0" layoutY="136.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Total Spent: " />
<Button layoutX="109.0" layoutY="301.0" mnemonicParsing="false" onAction="#toEditTrip" text="Add Expense..." />
<Button layoutX="373.0" layoutY="301.0" mnemonicParsing="false" text="View Expense List" />
<Text fx:id="budget" layoutX="139.0" layoutY="87.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Text" />
<Text fx:id="spent" layoutX="133.0" layoutY="136.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Text" />
</children></Pane>
</children>
</StackPane>
When I looked at other posts, they've told me to check the fx:id
in the FXML objects. 当我看其他文章时,他们告诉我要检查FXML对象中的
fx:id
。 I've done this and the fx:id
s are all correct. 我已经做到了,而
fx:id
都是正确的。 Why would I be getting a NullPointerException here? 为什么我会在这里得到NullPointerException?
The FXMLLoader
does not consider static fields as valid injection targets. FXMLLoader
不会将静态字段视为有效的注入目标。 The fields therefore need to be non-static. 因此,这些字段必须是非静态的。 If you need to access them in a static way (which you should avoid), you could still copy the values to static fields in the
initialize
method. 如果需要以静态方式访问它们(应避免使用),您仍然可以将这些值复制到
initialize
方法中的静态字段中。
You can find alternatives to using static fields for passing information here: Passing Parameters JavaFX FXML 您可以在此处找到使用静态字段传递信息的替代方法: 传递参数JavaFX FXML
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.