Light
Light

Reputation: 185

JavaFX and ProgressIndicator with fxml

I wonder from morning how to solve the problem. I have login aplication. When user waiting for login i want use processindicator. I used the second thread but it does not work

Main loader fxml

MainController

@FXML public StackPane MainStackPane;

    public void initialize(URL arg0, ResourceBundle arg1) {

    FXMLLoader loader = new FXMLLoader(this.getClass().getResource("/LoginForm/Login.fxml"));
    Pane pane = null;

    try {
        pane = loader.load();
    } catch (IOException e) {System.out.println(e.getMessage());}

    LoginController login = loader.getController();
    login.setMainController(this);

    setScreen(pane, true);
}

public void setScreen(Pane pane, boolean clean){

    MainStackPane.getChildren().addAll(pane);
    }

LoginForm:

private MainController mainController;
private void Zaloguj() throws IOException {
    String cryptUser = null, cryptPass = null;

    Test test = new Test(this.mainController);
    test.start();

    try {
        Thread.sleep(5000);
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    LoginSQL sql = new LoginSQL();`
    Byte LoginResult = sql.SQLselect(cryptUser, cryptPass);

    ...}

Class Test

public class test extends Service<Void>{

private MainController mainController;

public test(MainController mainController) {
    this.mainController = mainController;
}

protected Task<Void> createTask() {
    return new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            System.out.println("Service: START");

            ProgressIndicator p = new ProgressIndicator(); 

                     Platform.runLater(new Runnable() {
                         @Override public void run() {

                    mainController.MainStackPane.getChildren().addAll(p);
                     }});

                if (isCancelled()) {
                    mainController.MainStackPane.getChildren().remove(p);
                }
                return null;
            };};}}  

ProgressIndicator appears only in the next window after login. How to do it ?

Upvotes: 0

Views: 198

Answers (1)

JVon
JVon

Reputation: 694

JavaFX rendering happens in the main thread only. If you add the ProgressIndicator and then use Thread.sleep(), JavaFX won't render the indicator until Thread.sleep() is done. Also, if the login request hangs, JavaFX will also wait until the login request is complete before rendering.

What you have to do is to make sure to never interrupt/hang the main thread. Remove Thread.sleep, and also move your login request to a child thread. When the request is complete, notify the main thread so that it can remove the ProgressIndicator.

Upvotes: 1

Related Questions