NullPointerException occured with label.setText()

2019-08-18 01:55发布

问题:

I am trying to set the text to different labels using setText() method. I do tried to print the value to check whether the setText receives null or not. But I am able to successfully print the value in the console but why not able to set it to a label is what my question is.

Any suggestions would be helpful to resolve this NullPointerException.

PersonOverviewController.java

package passion.controllers;
import passion.models.Person;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;

public class PersonOverviewController{
    @FXML
    private TableView<Person> personTable;
    @FXML
    private TableColumn<Person, String> firstNameColumn;
    @FXML
    private TableColumn<Person, String> lastNameColumn;

    @FXML
    private Label firstNameLabel;
    @FXML
    private Label lastNameLabel;
    @FXML
    private Label streetLabel;
    @FXML
    private Label postalCodeLabel;
    @FXML
    private Label cityLabel;
    @FXML
    private Label birthdayLabel;

    public PersonOverviewController() {

    }

    @FXML
    private void initialize() {
        // Initialize the person table with the two columns.
        firstNameColumn.setCellValueFactory(cellData -> cellData.getValue().firstNameProperty());
        lastNameColumn.setCellValueFactory(cellData -> cellData.getValue().lastNameProperty());
        try{
            //showPersonDetails(null);
            //personTable.getSelectionModel().selectedItemProperty().addListener( (observable, oldValue, newValue) -> showPersonDetails(newValue));
            personTable.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Person>(){
                @Override
                public void changed(ObservableValue<? extends Person> observable, Person oldValue, Person newValue) {
                    System.out.println(newValue);
                    showPersonDetails(newValue);
                }
            });  
        }catch(NullPointerException e){
            e.printStackTrace();
        }
    }

    public void showTableViewData(MainApp mainApp) {
        personTable.setItems(mainApp.getPersonData());
    }

    public void showPersonDetails(Person person){
        Platform.runLater(new Runnable(){
            @Override
            public void run() {
                if(person != null){
                    System.out.println(person.getFirstName());
                    firstNameLabel.setText(person.getFirstName());
                    System.out.println("test");
                    lastNameLabel.setText(person.getLastName());
                    streetLabel.setText(person.getStreet());
                    postalCodeLabel.setText(Integer.toString(person.getPostalCode()));
                    cityLabel.setText(person.getCity());
                    birthdayLabel.setText(person.getBirthday().toString());
                }else{
                    firstNameLabel.setText("");
                    lastNameLabel.setText("");
                    streetLabel.setText("");
                    postalCodeLabel.setText("");
                    cityLabel.setText("");
                    birthdayLabel.setText("");
                }
            }
        });
    }
}

This is how I am loading the controller from MainApp.java

public void showPersonOverview(){
    try {
        FXMLLoader loader = new FXMLLoader();
        loader.setLocation(MainApp.class.getResource("/passion/viewControllers/PersonOverView.fxml"));

        AnchorPane personOverview = (AnchorPane)loader.load();
        root.setCenter(personOverview);

        PersonOverviewController personController = loader.getController();
        personController.showTableViewData(this);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

PersonOverview.fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>


<AnchorPane prefHeight="300.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="passion.controllers.PersonOverviewController">
   <children>
      <SplitPane dividerPositions="0.29797979797979796" layoutX="200.0" layoutY="70.0" prefHeight="300.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
        <items>
          <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
               <children>
                  <TableView fx:id="personTable" layoutX="-12.0" layoutY="49.0" prefHeight="200.0" prefWidth="200.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="-0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
                    <columns>
                      <TableColumn fx:id="firstNameColumn" prefWidth="75.0" text="First Name" />
                      <TableColumn fx:id="lastNameColumn" prefWidth="75.0" text="Last Name" />
                    </columns>
                     <columnResizePolicy>
                        <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
                     </columnResizePolicy>
                  </TableView>
               </children>
            </AnchorPane>
          <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
               <children>
                  <Label layoutX="14.0" layoutY="14.0" text="Person Details:" AnchorPane.leftAnchor="5.0" AnchorPane.topAnchor="5.0" />
                  <GridPane layoutX="34.0" layoutY="38.0" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0" AnchorPane.topAnchor="30.0">
                    <columnConstraints>
                      <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                      <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                    </columnConstraints>
                    <rowConstraints>
                      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                      <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                        <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                    </rowConstraints>
                     <children>
                        <Label text="First Name">
                           <GridPane.margin>
                              <Insets left="5.0" />
                           </GridPane.margin>
                        </Label>
                        <Label text="Last Name" GridPane.rowIndex="1">
                           <GridPane.margin>
                              <Insets left="5.0" />
                           </GridPane.margin>
                        </Label>
                        <Label text="Street" GridPane.rowIndex="2">
                           <GridPane.margin>
                              <Insets left="5.0" />
                           </GridPane.margin>
                        </Label>
                        <Label text="City" GridPane.rowIndex="3">
                           <padding>
                              <Insets left="5.0" />
                           </padding>
                        </Label>
                        <Label text="Postal Code" GridPane.rowIndex="4">
                           <GridPane.margin>
                              <Insets left="5.0" />
                           </GridPane.margin>
                        </Label>
                        <Label text="Birthday" GridPane.rowIndex="5">
                           <GridPane.margin>
                              <Insets left="5.0" />
                           </GridPane.margin>
                        </Label>
                        <Label fx:id="firstName" text="Label" GridPane.columnIndex="1">
                           <padding>
                              <Insets left="5.0" />
                           </padding>
                        </Label>
                        <Label fx:id="lastName" text="Label" GridPane.columnIndex="1" GridPane.rowIndex="1">
                           <GridPane.margin>
                              <Insets left="5.0" />
                           </GridPane.margin>
                        </Label>
                        <Label fx:id="street" text="Label" GridPane.columnIndex="1" GridPane.rowIndex="2">
                           <GridPane.margin>
                              <Insets left="5.0" />
                           </GridPane.margin>
                        </Label>
                        <Label fx:id="city" text="Label" GridPane.columnIndex="1" GridPane.rowIndex="3">
                           <GridPane.margin>
                              <Insets left="5.0" />
                           </GridPane.margin>
                        </Label>
                        <Label fx:id="postal" text="Label" GridPane.columnIndex="1" GridPane.rowIndex="4">
                           <GridPane.margin>
                              <Insets left="5.0" />
                           </GridPane.margin>
                        </Label>
                        <Label fx:id="birthday" text="Label" GridPane.columnIndex="1" GridPane.rowIndex="5">
                           <GridPane.margin>
                              <Insets left="5.0" />
                           </GridPane.margin>
                        </Label>
                     </children>
                  </GridPane>
                  <HBox layoutX="229.0" layoutY="244.0" spacing="5.0" AnchorPane.bottomAnchor="10.0" AnchorPane.rightAnchor="10.0">
                     <children>
                        <Button layoutX="229.0" layoutY="244.0" mnemonicParsing="false" text="New..." />
                        <Button layoutX="289.0" layoutY="244.0" mnemonicParsing="false" text="Edit..." />
                        <Button layoutX="351.0" layoutY="244.0" mnemonicParsing="false" text="Delete" />
                     </children>
                  </HBox>
               </children>
            </AnchorPane>
        </items>
      </SplitPane>
   </children>
</AnchorPane>

Console:

Person [firstName=StringProperty [value: Satya], lastName=StringProperty [value: Vema], street=StringProperty [value: some street], postalCode=IntegerProperty [value: 1234], city=StringProperty [value: some city], birthday=ObjectProperty [value: 1999-02-21]]
Person [firstName=StringProperty [value: Satya], lastName=StringProperty [value: Vema], street=StringProperty [value: some street], postalCode=IntegerProperty [value: 1234], city=StringProperty [value: some city], birthday=ObjectProperty [value: 1999-02-21]]
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
    at passion.controllers.PersonOverviewController$2.run(PersonOverviewController.java:69)
    at com.sun.javafx.application.PlatformImpl.lambda$null$170(Unknown Source)
    at com.sun.javafx.application.PlatformImpl$$Lambda$48/32693051.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$171(Unknown Source)
    at com.sun.javafx.application.PlatformImpl$$Lambda$47/2180324.run(Unknown Source)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$145(Unknown Source)
    at com.sun.glass.ui.win.WinApplication$$Lambda$36/3326003.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

回答1:

The connection (fx:id to variable name @FXML or @FXML("...")) is missing.

<Label text="First Name" fx:id="firstNameLabel">

Hence the components cannot be set to the FXML generated dialog's actual components.



回答2:

I think you are missing one part of code.

TextView firstNameLabel = (TextView)findIdById(R.id.yourTextViewIdInLayout);

And you must do that with all your widgets in order not to get a NullPointerException.