JavaFX登录校验成功跳转home.fxml时参数缺失问题问询
调整方案
你遇到的报错是因为switchtoHome方法需要传入ActionEvent参数才能获取到当前窗口对象,按以下步骤修改即可:
- 第一步:给
validatelogin方法添加ActionEvent入参,这个参数会在你点击登录按钮触发方法时自动传入。 - 第二步:在校验通过的if分支中,直接调用
switchtoHome并传入获取到的ActionEvent对象。 - 额外优化:修正原代码中JDBC驱动加载顺序问题,增加数据库资源关闭逻辑,避免资源泄漏。
修改后完整代码
package sample; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Node; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.stage.Stage; import javafx.event.ActionEvent; import java.io.IOException; import java.sql.*; public class Controller { @FXML private Button cancelbutton; @FXML private Label loginmessagelabel; @FXML private PasswordField password1; @FXML private TextField username1; @FXML private Stage stage; private Scene scene; private Parent root; public void validatelogin(ActionEvent event) throws SQLException, ClassNotFoundException, IOException { String jdbcURL = "jdbc:mysql://localhost/medibase"; String dbUsername = "root"; String dbPassword = "0852"; // 修正驱动加载顺序,放在获取连接前 Class.forName("com.mysql.jdbc.Driver"); Connection connection = null; PreparedStatement pst = null; ResultSet rs = null; try { connection = DriverManager.getConnection(jdbcURL,dbUsername,dbPassword); String inputUname = username1.getText(); String inputPsd = password1.getText(); pst=connection.prepareStatement("SELECT * FROM user_account WHERE username=? and password=?"); pst.setString(1, inputUname); pst.setString(2, inputPsd); rs = pst.executeQuery(); if(rs.next()){ loginmessagelabel.setText("Congratulations"); // 校验通过直接调用跳转方法,传入event参数 switchtoHome(event); } else{ loginmessagelabel.setText("Login failed"); } } finally { // 关闭数据库资源,避免泄漏 if(rs != null) rs.close(); if(pst != null) pst.close(); if(connection != null) connection.close(); } } public void switchtoHome(ActionEvent event)throws IOException { Parent root = FXMLLoader.load(getClass().getResource("home.fxml")); stage = (Stage)((Node)event.getSource()).getScene().getWindow(); scene=new Scene(root); stage.setScene(scene); stage.show(); } }
FXML绑定说明
不需要修改FXML中登录按钮的onAction绑定,保持绑定validatelogin即可,JavaFX会自动把点击事件的ActionEvent对象传入方法。
内容的提问来源于stack exchange,提问作者Banchi Secret
相关产品推荐
相关产品推荐

