Java label.setText NullPointerException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22546028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:24:16  来源:igfitidea点击:

label.setText NullPointerException

javanullpointerexceptionjavafxfxmlsettext

提问by twin_suns

Hi first time here but here goes:

嗨,第一次来这里,但这里是:

I have a JavaFX application that changes the FXML UI labels dynamically and the data is pulled from a Player class.

我有一个 JavaFX 应用程序,它动态更改 FXML UI 标签,并且数据是从 Player 类中提取的。

The two classes in question are Player.javaand InterfaceHandler.java.

有问题的两个类是Player.javaInterfaceHandler.java

The player class stores player details and I want to pass the details to the Interface class which sets the text on the labels.

播放器类存储播放器详细信息,我想将详细信息传递给在标签上设置文本的接口类。

As a test my FXML UI just has a button and two labels.

作为测试,我的 FXML UI 只有一个按钮和两个标签。

If it click the button it calls the handleButtonmethod it sets locationLabelto "Town" fine.

如果它单击按钮,它会调用handleButton它设置locationLabel为“城镇”的方法。

However if I call the locationLabel()method in my Player class I get a NullPointerException when nameLabel.setText(name)is called. Through debugging I find that the name string in the Interface class is what it should be "Dan".

但是,如果我locationLabel()在 Player 类中调用该方法,则在调用时nameLabel.setText(name)会收到 NullPointerException 。通过调试发现Interface类中的name字符串应该是“Dan”。

Can anyone help?

任何人都可以帮忙吗?

Main class:

主要类:

public class Main extends Application {

    public void start(final Stage mainStage) throws Exception {

        Parent root = FXMLLoader.load(getClass().getResource("MainScreen.fxml"));
        Scene scene = new Scene(root);
        mainStage.setTitle("Main Screen");
        mainStage.setScene(scene);
        mainStage.show();    
    }

public static void main(String[] args) {
        launch(args);
    }
}

Player class:

球员等级:

public class Player{

InterfaceHandler ui = new InterfaceHandler();   

 public void setNameLabel() {

    String name = "Dan";
    ui.setName(name);
}

InterfaceHandler class:

接口处理器类:

    public class InterfaceHandler implements Initializable {

       public Label nameLabel;
       public Label locationLabel;    

public void handleButton(ActionEvent event) throws IOException {        

        locationLabel.setText("Town");
    }

public void setName(String name){       
        nameLabel.setText(name);
    }    
}

MainScreen.fxml:

主屏幕.fxml:

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

    <?import java.lang.*?>
    <?import java.net.*?>
    <?import java.util.*?>
    <?import javafx.scene.*?>
    <?import javafx.scene.control.*?>
    <?import javafx.scene.effect.*?>
    <?import javafx.scene.image.*?>
    <?import javafx.scene.layout.*?>
    <?import javafx.scene.text.*?>

    <AnchorPane id="AnchorPane" prefHeight="629.0" prefWidth="600.0" snapToPixel="true" style="-fx-background-color:  beige;" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="application.InterfaceHandler">
      <children>            
        <Button fx:id="button1" layoutX="512.0" layoutY="381.0" minWidth="14.0" mnemonicParsing="false" onAction="#handleButton" prefHeight="30.0" prefWidth="51.0" text="Town" visible="true" />        

        <Label fx:id="nameLabel" layoutX="57.0" layoutY="8.0" prefWidth="216.0" text="blank" />
        <Label fx:id="locationLabel" layoutX="68.0" layoutY="27.0" prefWidth="193.0" text="blank" />
      </children>
    </AnchorPane>

采纳答案by Branislav Lazic

It's because you didn't properly inject your Labelsfrom FXML file.

这是因为您没有正确地Labels从 FXML 文件中注入您的文件。

Annotate your Labelvars. with FXMLannotation:

注释你的Label变量。与FXML注释:

public class InterfaceHandler implements Initializable {
    @FXML
    public Label nameLabel;
    @FXML
    public Label locationLabel;    

    public void handleButton(ActionEvent event) throws IOException {        
        locationLabel.setText("Town");
    }

    public void setName(String name){       
        nameLabel.setText(name);
    }    
}

Also, InterfaceHandler is a controller which you reference with fx:controllerin your FXML. This instructs the FXMLLoader to create a new instance of the InterfaceHandler when the loader loads its FXML. So don't create a new InterfaceHandler in your Player class, instead make InterfaceHandler a constructor parameter for Player and use loader.getController to get the InterfaceHandler controller instance out of the FXMLLoader.

此外,InterfaceHandler 是您fx:controller在 FXML 中引用的控制器。这将指示 FXMLLoader 在加载器加载其 FXML 时创建 InterfaceHandler 的新实例。因此,不要在您的 Player 类中创建新的 InterfaceHandler,而是将 InterfaceHandler 设为 Player 的构造函数参数,并使用 loader.getController 从 FXMLLoader 中获取 InterfaceHandler 控制器实例。

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("MainScreen.fxml"));
Parent root = (Parent)loader.load();
Player player = new Player(loader.getController());
Scene scene = new Scene(root);

. . .

public class Player {
  private InterfaceHandler ui;   

  public Player(InterfaceHandler ui) {
    this.ui = ui;
  }

  public void setNameLabel() {
    String name = "Dan";
    ui.setName(name);
  }
}

回答by Yash Kalia

I had a similar problem but turns out that I had made the label as a static attribute and when I removed the static part it fixed the nullpointer exeption.

我有一个类似的问题,但事实证明我已将标签作为静态属性,当我删除静态部分时,它修复了空指针异常。