尝试在 Text 对象上使用 .setText 时出现 NullPointerException

NullPointerException when attempting to use .setText on a Text object

每当我尝试在控制器 class 的文本字段上使用 .setText 时,我都会收到 NullPointerException。 这是我的控制器 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;
    }
}

这是我的 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>

当我查看其他帖子时,他们告诉我检查 FXML 对象中的 fx:id。我已经这样做了, fx:id 都是正确的。为什么我会在这里得到 NullPointerException?

FXMLLoader 不将静态字段视为有效注入目标。因此,这些字段需要是非静态的。如果您需要以静态方式访问它们(您应该避免这种方式),您仍然可以将值复制到 initialize 方法中的静态字段。

您可以在此处找到使用静态字段传递信息的替代方法:Passing Parameters JavaFX FXML