简体   繁体   中英

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. 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:

 <?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. I've done this and the fx:id s are all correct. Why would I be getting a NullPointerException here?

The FXMLLoader does not consider static fields as valid injection targets. 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.

You can find alternatives to using static fields for passing information here: Passing Parameters JavaFX FXML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM