我有一段代码,JavaFX 中的登录表单。它只是一个原型(prototype),它基于尚未涵盖此类主题的教程。我想添加一个 TextField 验证,我是这样做的:
Button btn = new Button("Login");
HBox hBtn = new HBox(10);
hBtn.setAlignment(Pos.BOTTOM_RIGHT);
hBtn.getChildren().add(btn);
grid.add(hBtn, 1, 4);
final Text actiontarget = new Text();
grid.add(actiontarget, 1, 6);
if (userTextField.getText().trim().isEmpty() && !pwField.getText().trim().isEmpty()) {
btn.setOnAction(event
-> {
actiontarget.setFill(Color.FIREBRICK);
actiontarget.setText("No login provided!");
});
} else if (pwField.getText().trim().isEmpty() && !userTextField.getText().trim().isEmpty()) {
btn.setOnAction(event
-> {
actiontarget.setFill(Color.FIREBRICK);
actiontarget.setText("Please provide a password!");
});
} else if (userTextField.getText().trim().isEmpty() && pwField.getText().trim().isEmpty()) {
btn.setOnAction(event
-> {
actiontarget.setFill(Color.FIREBRICK);
actiontarget.setText("Please provide login and password!");
});
} else {
btn.setOnAction(event
-> {
actiontarget.setFill(Color.GREEN);
actiontarget.setText("Login succesfull");
});
}
问题是,此代码始终返回第三个条件的文本:请提供登录名和密码!
,这些字段中的输入并不重要。我可以只提供密码,只提供登录名,两者都提供,或者两者都不提供,结果将始终相同。
我在这里遗漏了什么吗?这是一种(非常)错误的方法吗?或者我只是累了,应该去 sleep 了?
干杯!
最佳答案
if/else if
在您创建 GUI 时进行评估。
这意味着已检查您初始化 TextField
时使用的值(或默认值)。
将检查移至事件处理程序以检查单击按钮时的值:
...
grid.add(actiontarget, 1, 6);
btn.setOnAction(evt -> {
String user = userTextField.getText().trim();
String password = pwField.getText().trim();
if (!(user.isEmpty() || password.isEmpty())) {
actiontarget.setFill(Color.GREEN);
actiontarget.setText("Login succesfull");
} else {
actiontarget.setFill(Color.FIREBRICK);
if (user.isEmpty()) {
actiontarget.setText(password.isEmpty() ? "Please provide login and password!" : "No login provided!");
} else {
actiontarget.setText("Please provide a password!");
}
}
});
关于JavaFX:如果 TextField 的条件在 ActionEvent 上无法正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54202499/