JAVA FX - Service.start()不会在单独的线程中运行

时间:2015-03-28 20:58:50

标签: java javafx-8

我有应用程序,我在primaryStage中启动我的场景。

当用户单击“确定”按钮时,我创建了一个服务,然后启动它。该服务调用WebService并获得响应。 我已经看到,在调用start()之后,主流不会继续,并且会立即调用createTask()并阻止所有UI。这是我的代码:

按下按钮时的代码

@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();
    }

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 个答案:

答案 0 :(得分:0)

我发现错误的地方,这是 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;
            }
        };
    }
}