JavaFX登录访问被拒绝

时间:2018-06-23 05:04:42

标签: java javafx

当我尝试使用Redbull作为用户名并以pass123作为密码登录时,它没有显示已授予访问权限的消息,而是转到else语句并显示访问被拒绝的消息

    Label usernameLb = new Label("Username:");
    GridPane.setConstraints(usernameLb, 0, 0);

    TextField usernameTf = new TextField();
    usernameTf.setPromptText("Username");
    GridPane.setConstraints(usernameTf , 1, 0);

    Label passLb = new Label("Password:");
    GridPane.setConstraints(passLb, 0, 1);

    TextField passTf = new TextField();
    passTf.setPromptText("Password");
    GridPane.setConstraints(passTf, 1, 1);

    Button loginBtn = new Button("Login");
    loginBtn.setOnAction(e -> {

        String username = usernameTf.getText();
        String password = passTf.getText();

        if (username == "redbull" && password == "pass123"){

            System.out.println(username + "\n" + password);
            JOptionPane.showMessageDialog(null, 
                    "Access Granted", " ", JOptionPane.PLAIN_MESSAGE);

        } else {

            System.out.println(username + "\n" + password);
            JOptionPane.showMessageDialog(null, 
                    "Access Denied", " ", JOptionPane.PLAIN_MESSAGE);
        }
    });

    GridPane.setConstraints(loginBtn, 1, 2);

    gridPane.getChildren().addAll(usernameLb, 
    usernameTf, passLb, passTf, loginBtn);

    Scene scene1 = new Scene(gridPane, 300, 200);
    window.setScene(scene1);
    window.show();

}

1 个答案:

答案 0 :(得分:-2)

比较两个字符串的值时,请使用.equals()

(username.equals("redbull") && password.equals("pass123"))