【问题标题】:JavaFX: if condition forTextField not working properly on ActionEvent?JavaFX:如果 TextField 的条件在 ActionEvent 上无法正常工作?
【发布时间】:2019-06-09 16:19:13
【问题描述】:

我有一段代码,JavaFX 中的登录表单。它只是一个原型,它基于一个尚未涵盖此类主题的教程。我想添加一个 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");
    });
}

问题是,这段代码总是从第三个条件返回文本:Please provide login and password!,这些字段中的输入无关紧要。我可以只提供密码,只提供登录名,两者都提供,或者两者都不提供,结果总是一样的。

我在这里遗漏了什么吗?这是一个(非常)错误的方法吗?还是我只是累了,该睡觉了?

干杯!

【问题讨论】:

  • 根据if-statement 设置ButtonOnAction 很可能是一种不正确的处理方式。如果要设置actiontarget 的文本,则需要将if-statement 放入TextField TextProperty 侦听器中。您还需要取消setOnActions。只设置actontarget 填充和文本。

标签: java validation javafx textfield


【解决方案1】:

if/else if 在您创建 GUI 时进行评估。

这意味着检查您已使用(或默认值)初始化 TextFields 的值。

将检查移至事件处理程序以在单击按钮时检查值:

...
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!");
        }
    }
});

【讨论】:

  • 像魅力一样工作!
猜你喜欢
  • 2016-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多