label.setText NullPointerException

拥有回忆 提交于 2019-11-29 07:41:42
Branislav Lazic

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

Annotate your Label vars. with FXML annotation:

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

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

Just add something in the label, space or anything but not null.

<Label . . . " text="ANYTHING"  . . . />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!