开发者

JavaFX : How to store String values globally

I am having trouble passing user name and role when switching scenes. The name and role is retrieved from the database when user logs in, then it gets displayed in a Label in the Dashboard page. But when I switch from Dashboard to another scene, and then come back to the Dashboard, the Labels are null. I'm not entirely sure how to store the Label values globally, so that it will remain the same even when I access the Dashboard from a different scene.

login.java

@FXML
private void onClick(ActionEvent event) throws IOException, Exception {

    String userid = id.getText();
    String password = pass.getText();

    try {
        Connection con = getConnection();
        PreparedStatement st = con.prepareStatement("SELECT * FROM allusers WHERE ID =? AND Password=?");
        st.setString(1, userid);
        st.setString(2, password);
        ResultSet rs = st.executeQuery();

        if (rs.next()) {
            String name = rs.getString("Name");
            String role = rs.getString("Role");
            FXMLLoader loader = new FXMLLoader(getClass().getResource("Dashboard.fxml"));
            root = loader.load();
            Dashboard dash = loader.getController();
            dash.setName(name, role);
            stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
            scene = new Scene(root);
            stage.setScene(scene);
            stage.show();

            } else {
                System.out.println("user not found.");
        }
        st.close();
        rs.close();
      开发者_Go百科  con.close();
    } catch (SQLException e) {
    }
}

Dashboard.java

public void setName(String name, String role) {
    fullname.setText(name);
    userrole.setText(role);       
}

Say I'm from another scene and want to go back to Dashboard :

    @FXML
public void backToDashboard(ActionEvent event) throws IOException {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("Dashboard.fxml"));
    root = loader.load();
    Dashboar dash = loader.getController();
    stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
    scene = new Scene(root);
    stage.setScene(scene);
    stage.show(); // user name and role are now null
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜