Controller.java
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
public class Controller {
public TextField txtField;
public PasswordField passField;
public Button btn;
public Label access;
private String USNM = "crimsoncoder";
private String PASS = "toor";
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬问题从这里开始▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
private String usnm = txtField.getText();
private String pass = passField.getText();
private String acc = access.getText();
private final String ACCESS_GRANTED = "/ACCESS_GRANTED/";
private final String ACCESS_DENIED = "|/?ACCESS_DENIED?/|";
public void onClick() {
if (usnm.equals(USNM)) {
if (pass.equals(PASS)) {
acc = ACCESS_GRANTED;
} else {
acc = ACCESS_DENIED;
}
} else {
acc = ACCESS_DENIED;
}
}
}
在Controller.java中声明
getText()
,setText()
和toString()
变量后,调用方法usnm
,pass
和acc
返回NullPointerException
。知道为什么会这样吗?新代码:
public class Controller {
@FXML
private TextField txtField;
@FXML
private PasswordField passField;
@FXML
private Button btn;
@FXML
private Label access;
private String USNM = "crimsoncoder";
private String PASS = "toor";
private static final String ACCESS_GRANTED = "/ACCESS_GRANTED/";
private static final String ACCESS_DENIED = "|/?ACCESS_DENIED?/|";
public void onClick() {
String usnm = txtField.getText();
String pass = passField.getText();
if (usnm.equals(USNM)) {
if (pass.equals(PASS)) {
access.setText(ACCESS_GRANTED);
} else {
access.setText(ACCESS_DENIED);
}
} else {
access.setText(ACCESS_DENIED);
}
}
}
最佳答案
实际上,这里的设计存在很多问题。首先,您试图在txtField
和passField
控件的值实际存在于场景中之前对其进行访问。
使用JavaFX和FXML,在初始化场景之前,不会构建(或注入)这些控件并将其提供给控制器。
控件引用也应为private
并使用@FXML
关键字进行注释,如下所示:
@FXML
private TextField txtField;
这实际上告诉Java
TextField
已在关联的FXML文档中定义。在单击
LOGIN
按钮之后,您需要获取用户名和密码字段的值,因此更新您的onClick()
方法以获取当时的值:public void onClick() {
String usnm = txtField.getText();
String pass = passField.getText();
String acc;
if (usnm.equals(USNM)) {
if (pass.equals(PASS)) {
acc = ACCESS_GRANTED;
} else {
acc = ACCESS_DENIED;
}
} else {
acc = ACCESS_DENIED;
}
System.out.println(acc);
}
因此,对于稍微更好的
Controller.java
,您可以使用以下代码:public class Controller {
@FXML
public TextField txtField;
@FXML
public PasswordField passField;
@FXML
public Button btn;
@FXML
public Label access;
private String USNM = "crimsoncoder";
private String PASS = "toor";
private static final String ACCESS_GRANTED = "/ACCESS_GRANTED/";
private static final String ACCESS_DENIED = "|/?ACCESS_DENIED?/|";
public void onClick() {
String usnm = txtField.getText();
String pass = passField.getText();
String acc;
if (usnm.equals(USNM)) {
if (pass.equals(PASS)) {
acc = ACCESS_GRANTED;
} else {
acc = ACCESS_DENIED;
}
} else {
acc = ACCESS_DENIED;
}
System.out.println(acc);
}
}
关于java - JavaFX getText(),setText(),toString()提供空指针,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50660863/