If 语句在 Java 中不使用 .equals 并且总是显示 else 语句的答案

0 java javafx

我自己正在学习 Java,并且正在尝试像应用程序一样登录。if 语句不起作用,但 else 语句始终有效。

这是代码:

package Lessons;

public class Main extends Application {

    Stage window;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        window = primaryStage;
        window.setTitle("Sign in");

        TextField nameInput = new TextField();

        Button button = new Button("Sign In");

        VBox layout = new VBox(10);
        layout.setPadding(new Insets(20, 20, 20,20));
        layout.getChildren().addAll(nameInput, button);

        Scene scene = new Scene(layout, 600, 600);
        window.setScene(scene);
        window.show();

        //Checks the username
        String username = "thomas";
        if (nameInput.getText().equals(username)) {
            button.setOnAction(e -> CorrectUsernameReplier.display());}
        else {
            button.setOnAction(e -> WrongUsernameReplier.display());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我没有显示我导入的内容,因为我认为它们没有必要。

这是来自CorrectUsernameReplier的代码

public static void display() {
    Stage window = new Stage();

    //Replies to correct username
    window.setTitle("Correct username");
    window.initModality(Modality.APPLICATION_MODAL);
    StackPane layout = new StackPane();
    Scene scene = new Scene(layout, 200, 200);
    Label label = new Label("Signed In");
    layout.getChildren().add(label);
    window.setScene(scene);
    window.showAndWait();
Run Code Online (Sandbox Code Playgroud)

这是来自WrongUsernameReplier的代码

public static void display() {
    Stage window = new Stage();


    //Replies to incorrect username
    window.setTitle("Incorrect username");
    window.initModality(Modality.APPLICATION_MODAL);
    StackPane layout1 = new StackPane();
    Scene scene1 = new Scene(layout1, 200, 200);
    Label label = new Label("Incorrect Username. Please try again.");
    layout1.getChildren().add(label);
    window.setScene(scene1);
    window.showAndWait();
Run Code Online (Sandbox Code Playgroud)

如果错误是什么,这里是图像:

“thomas”在 TextField 中,上面代码中的用户名字符串也是“thomas”。但它显示了您看到的错误。

“thomas”在 TextField 中,上面代码中的用户名字符串也是“thomas”。 但它显示了您看到的错误。

这是第二张图:

这是我没有输入任何内容的屏幕截图。而这里的回应是正确的。

这是我没有输入任何内容的屏幕截图。 而这里的回应是正确的。

你能帮我弄清楚我的代码有什么问题吗?

Smu*_*tje 5

由于在if创建视图时处理语句,因此button.setOnAction(e -> WrongUsernameReplier.display());每次都无条件地执行。您缺少的是,检查用户名是否正确只能在按下按钮时进行,而不是在初始化 UI 时进行:

button.setOnAction(e -> {
    String username = "thomas";

    if (nameInput.getText().equals(username)) {
        CorrectUsernameReplier.display();
    } else {
        WrongUsernameReplier.display();
    }
});
Run Code Online (Sandbox Code Playgroud)

或 JavaFX 中的类似内容。