使用label.setText()发生NullPointerException [英] NullPointerException occured with label.setText()

查看:140
本文介绍了使用label.setText()发生NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用setText()方法将文本设置为不同的标签。我试图打印该值以检查setText是否收到null。但我能够在控制台中成功打印该值,但为什么不能将其设置为标签就是我的问题。

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.

任何建议都有助于解决这个NullPointerException。

Any suggestions would be helpful to resolve this NullPointerException.

PersonOverviewController.java

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("");
                }
            }
        });
    }
}

这就是我从MainApp加载控制器的方法。 java

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

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>

控制台:

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)


推荐答案

连接( fx:id 到变量名 @FXML 缺少@FXML(...)

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

因此,组件无法设置为FXML生成对话框的实际组件。

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

这篇关于使用label.setText()发生NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆