我有一个表,它是我的editButton操作方法:

    public void editAction() {
    if (table.getSelectedRow() > -1) {
        String oldFName = table.getValueAt(table.getSelectedRow(), 1).toString();
        String oldLName = table.getValueAt(table.getSelectedRow(), 2).toString();
        String oldGender = table.getValueAt(table.getSelectedRow(), 3).toString();
        System.out.println(oldFName);  // prints correctly
        System.out.println(oldLName);  // prints correctly
        System.out.println(oldGender);  // prints correctly

        AddUserDialog userDialog = new AddUserDialog(this, oldFName, oldLName, oldGender);
    } else JOptionPane.showMessageDialog(null, "Select A Row");
}


我的AddUserDialog类:

    public AddUserDialog(JFrame owner, String oldFname, String oldLname, String oldGender) {
    super(owner, "Edit User Information", true);
    fNameTf.setText(oldFname);     // First name text field
    lNameTf.setText(oldLname);     // Last name text field
    if (oldGender.equals("Male")) maleRb.setSelected(true);  //Male radio Button
    else femaleRb.setSelected(true);                   //Female radio Button

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setLocation(400, 100);
    setVisible(true);
    pack();
}
...
}


现在,当我选择一行并单击“编辑”按钮时,旧的名字,旧的姓氏和性别会在我的控制台上正确打印,但是我的IDE表示该异常在这里:

fNameTf.setText(oldFname);       // why is Null here?!


更新资料
第二种方式:

    public void editAction() {
    if (table.getSelectedRow() > -1) {
        String oldFName = table.getValueAt(table.getSelectedRow(), 1).toString();
        String oldLName = table.getValueAt(table.getSelectedRow(), 2).toString();
        String oldGender = table.getValueAt(table.getSelectedRow(), 3).toString();
        System.out.println(oldFName);  // prints correctly
        System.out.println(oldLName);  // prints correctly
        System.out.println(oldGender);  // prints correctly
        AddUserDialog userDialog = null;

        userDialog.setfName(oldFName);  // Why is null here?!
        userDialog.setlName(oldLName);
        userDialog.setGender(oldGender);
        userDialog = new AddUserDialog(this, userDialog.getfName(), userDialog.getlName(), userDialog.getGender());

    } else JOptionPane.showMessageDialog(null, "Select A Row");
}


现在NullPointerException在这里:

userDialog.setfName(oldFName);


如何解决呢?

最佳答案

fNameTfnull构造函数中的AddUserDialog。您没有初始化fNameTf

编辑:

AddUserDialog userDialog = new AddUserDialog(this, userDialog.getfName(), userDialog.getlName(), userDialog.getGender());

userDialog.setfName(oldFName);

10-08 19:20