JAVA FX - Hide stage lost service task response

2019-09-07 06:04发布

问题:

In this post i was answer why my UI was blocking after service.start() call, and it is resolved. Now I have another "little" problem... after start() the service I will hide/close the stage to run the application on TrayIcon.

I've noticed that with hide()/close() the stage, the Service will be blocked and never go in SUCCEEDED status. I've tried to remove this call and all works.

How I can hide()/close() my stage without block the Service thread and so receive the answer for minimize on tray?

@FXML
    private void handleRegisterButton() {

        User newUser = new User();
        newUser.setUsername(usernameTextField.getText());
        newUser.setGroup(groupChoicheBox.getSelectionModel().getSelectedItem());
        newUser.setMachineName(machineNameTextField.getText());

        this.mainApp.registerNewUser(newUser); // this is primaryStage from Main

        RegisterUserInvocation service = new RegisterUserInvocation(newUser);

        service.stateProperty().addListener(new InvalidationListener() {
            @Override
            public void invalidated(Observable observable) {
                System.out.println("Task value " + service.getState());
                if(service.getState().equals(Worker.State.SUCCEEDED)) {
                    mainApp.showMessageOnTray("Lan Alert", "Attivo!", MessageType.INFO); // Handler method to show TrayMessage
                }
            }
        });

        service.start();

        /* IF I REMOVE THIS THE APPLICATION WORKS. SURE, THE WINDOW REMAIN VISIBLE*/
        this.mainApp.getPrimaryStage().close();
    }

回答1:

You need to invoke Platform.setImplicitExit(false), otherwise the JavaFX runtime will shut down when you close the last stage.

See this sample for using a TrayIcon and JavaFX.