JAVA FX - Service.start() wont run in a separate thread

蓝咒 提交于 2019-12-12 01:52:00

问题


I have and application and i start my scene in the primaryStage.

When the user click OK button, I create a Service and after that, I start it. This service make a call to WebService and get me the response. I've seen that after the start() is called, the main flow do not continue and createTask() is called immediately and all my UI is blocked. This is my code:

Code when I press the button

@FXML
    private void handleRegisterButton() {

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

        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))
                    System.out.println("SUCCEEDED");
            }
        });

        service.start();

        this.mainApp.getPrimaryStage().close();
    }

Code of RegisterUserInvocation

public class RegisterUserInvocation extends Service<Integer>{
    private User user;

    public RegisterUserInvocation(User user) {
        this.user = user;
    }

    @Override
    protected Task<Integer> createTask() {
        String url = "http://localhost:8080/LANServer/services/Rest/user/";
        Client client = ClientBuilder.newClient();      
        Integer resp = client.target(url).request().post(Entity.entity(user, MediaType.APPLICATION_JSON), Integer.class);

        return new Task<Integer>() {
            @Override
            protected Integer call() throws Exception {
                return resp;
            }
        };
    }
}

回答1:


I've found where i wrong, this is the new code of RegisterUserInvocation:

public class RegisterUserInvocation extends Service<Integer>{
    private User user;

    public RegisterUserInvocation(User user) {
        this.user = user;
    }

    @Override
    protected Task<Integer> createTask() {
        return new Task<Integer>() {
            @Override
            protected Integer call() throws Exception {
                String url = "http://localhost:8080/LANServer/services/Rest/user/";
                Client client = ClientBuilder.newClient();      
                Integer resp = client.target(url).request().post(Entity.entity(user, MediaType.APPLICATION_JSON), Integer.class);

                return resp;
            }
        };
    }
}


来源:https://stackoverflow.com/questions/29322542/java-fx-service-start-wont-run-in-a-separate-thread

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!