[英]how can switch between scenes if the condition is true JavaFX
我正在使用 javaFX 创建登录系统。 当用户输入正确的用户名和密码时,系统应该打开一个名为“Dashbord”的新场景。 这是我的登录功能
public void validatelogin() throws SQLException, ClassNotFoundException, IOException {
String jdbcURL = "jdbc:mysql://localhost/medibase";
String username = "root";
String password = "0852";
Connection connection = DriverManager.getConnection(jdbcURL,username,password);
Class.forName("com.mysql.jdbc.Driver");
String uname = username1.getText();
String psd = password1.getText();
pst=connection.prepareStatement("SELECT * FROM user_account WHERE username=? and password=?");
pst.setString(1, uname);
pst.setString(2, psd);
rs = pst.executeQuery();
if(rs.next()){
//loginmessagelabel.setText("Congratulations");
switchtoSC1(null);
} else{
loginmessagelabel.setText("Login failed");
}
}
当用户输入正确的用户名和密码时,我调用了 switchtoSC1 方法,但这不起作用。 这是方法,,
public void switchtoSC1(ActionEvent event)throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("Dashboard.fxml"));
stage = (Stage)((Node)event.getSource()).getScene().getWindow();
scene=new Scene(root);
stage.setScene(scene);
stage.show();
}
正如@James_D 已经说过你必须传递一个非空事件来获取舞台变量,你还应该在同一舞台改变场景而不是再次创建一个新的舞台,因为这不会处理资源并且会减慢应用程序。
另外,查看您的登录代码,我建议您仅通过用户名获取数据库行,然后将密码(如果它们是密码散列或加盐散列更好)作为变量进行比较。 这是因为结果集可能很棘手,而且您不想基于它进行身份验证。
public void validateLogin(Connection conn) {
String username = username1.getText(); // you should obviously prevent username
// duplication in the signin page code
String password = password1.getText();
String queryStr = "select * from user_account where username=?";
try (PreparedStatement prepStmt = conn.prepareStatement(queryStr)) {
prepStmt.setString(1, username);
ResultSet rset = prepStmt.executeQuery();
if (!rset.next())
throw new LoginFailedException(); // the username doesn't match any database
// row
byte[] passwordHash = rset.getBytes("passwordColumn"); // get the password hash from
// the resultset
byte[] inputHash = someHashingFunction(password); // get the input hash with the same
// function used to store passwords,
// so that you get the same result
// inputting the same password
checkHashes(passwordHash, inputHash))
switchScene(); // some method or block to switch scenes
} catch (LoginFailedException e) {
// show some error scene here
}
}
public void checkHashes(byte[] passwordHash, byte[] inputHash) throw LoginFailedException {
for (int x = 0; x < inputHash.length; x++) {
if (passwordHash[x] != inputHash[x]) {
throw new LoginFailedException();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.