首页 > 解决方案 > 为什么出现 NullPointerException 然后尝试 setText?

问题描述

尝试使用 setText 方法将数据设置为TextField. 我想要

  1. 向地图添加标志。
  2. 然后出现窗口,我将数据输入到TextFields。
  3. 在按下标志时,此窗口显示 s 中的填充数据TextField,但问题是我试图按下标志以获取信息,NullPointerException显示出来。

能有问题吗?

setText打开窗口控制器的方法:
NullPointerException显示在setCountry方法的第一行

public class InfoController {

    @FXML
    private TextField idField, nameField, countryField;

    @FXML
    private Button saveButton;
    private String company, country;
    private int code;

    @FXML
    void onClickClear(ActionEvent event) {
        nameField.setText("");
        countryField.setText("");
        idField.setText("");
    }

    @FXML
    void onSaveClick(ActionEvent event) {
        if(parseInputs()) {

            Information.setCode(code);
            Information.setCompany(company);
            Information.setCountry(country);

            nameField.setText("");
            countryField.setText("");
            idField.setText("");
        }
        Stage stage = (Stage) saveButton.getScene().getWindow();
        stage.close();
    }

    private boolean parseInputs() {
        try {
            company = nameField.getText();
            country = countryField.getText();
            code = Integer.parseInt(idField.getText());

            if(nameField.getText().isEmpty() || countryField.getText().isEmpty() || idField.getText().isEmpty()) return false;
        }
        catch (Exception e) {
            System.out.println("Unable to save information");
            return false;
        }
        return true;
    }

    public void setCountry(String data) {
        countryField.setText(data);
        countryField.setEditable(false);
    }

位置,在打开窗口之前尝试设置文本的位置。

@FXML
void addFlag(ActionEvent event) {
    addingFlag.pinFlag(imageView, anchPane);
    flagList = addingFlag.listOfFlags();

    Button flg = flagList.get(0);
    flg.setOnMouseClicked(eve -> {
        String getCode = Integer.toString(Information.getCode());

        info.setCountry(Information.getCountry());
        info.setCode(getCode);
        info.setCompany(Information.getCompany());

        addingFlag.openInformationWindow();
    });
}

标签: javafxsettext

解决方案


推荐阅读