这是我做过的一个小的Java程序登录示例,当我运行它并按JFXButton登录时,发生了大约1秒钟的延迟,如图所示,知道该延迟之后,该程序已成功连接并进行查询

this happens to the JFXButton for the second delay

之后,当我再次按下该按钮时,它会快速流畅地运行,直到我停下来再次运行。

请注意,将我带到另一个场景的注册JFXButton可以正常工作,并且我是该领域的新手。谢谢 :)

    public void initialize(URL location, ResourceBundle resources) {
        progressBar.setStyle("-fx-background-color: green");
        progressBar.setVisible(false);
        wrngPassLbl.setVisible(false);
        handler = new DBHandler();
    }

    @FXML
    public void loginAction(ActionEvent e) {

        progressBar.setVisible(true);
        PauseTransition pt = new PauseTransition();
        pt.setDuration(Duration.seconds(3));
        pt.setOnFinished(ex -> {
            System.out.println("Login successful.");

        });
        pt.play();

        String q1 = "select * from [User] where userName=? and userPass=?";
        dbConnection = handler.getConnection();

        try {
            pst = dbConnection.prepareStatement(q1);
            pst.setString(1, usrTxt.getText());
            pst.setString(2, passTxt.getText());
            ResultSet result = pst.executeQuery();

            int count = 0;
            while (result.next()) {
                count++;
            }

            if (count == 1) {
                System.out.print("Connection is successfully established");

            } else if (count == 0) {
                System.out.print("wrong username or password");
            }
            pst.close();
            dbConnection.close();
        } catch (SQLException ex) {
            ex.printStackTrace();

        }
    }


这是DBHanler类(用于连接)

public class DBHandler extends Configs {

    Connection dbConnection;

    public Connection getConnection() {

        Properties prop = new Properties();
        prop.setProperty("user", dbUser);
        prop.setProperty("password", dbPass);
        prop.setProperty("useSSL", "false");
        prop.setProperty("autoReconnect", "true");

        String connectionString = "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + dbName;

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }

        try {
            dbConnection = DriverManager.getConnection(connectionString,prop);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return dbConnection;
    }
}

最佳答案

我的问题已使用Concurrency in javaFX修复,如@Slaw建议

08-07 06:36