Soul85 Soul85 - 3 months ago 29
HTTP Question

How to disable button event on JavaFX 8 until http response

Using JavaFx8 i have a button that send a http request. I want to disable this button until i received the answer from the server. My situation is the following:

HBox boxRep = new HBox();
...
boxRep.setOnMousePressed((event) ->{
String responseHttpCode = "";
responseHttpCode = MySendHttp(ip, port, request);
...
});


My method (MySendhttp) return the String with the http code status (200,404...). I dont't want to send another request until the server answer.

Thanks

Answer

Run it in a task, on a background thread, and process the response in the onSucceeded handler:

boxRep.setOnMousePressed(event -> {
    Task<String> httpTask = new Task<String>() {
        @Override
        public String call() throws Exception {
            return MySendHttp(ip, port, request);
        }
    };

    Thread thread = new Thread(httpTask);

    httpTask.setOnSucceeded(e -> {
        boxRep.setDisable(false);
        String responseCode = httpTask.getValue();
        // process...
    });


    boxRep.setDisable(true);

    thread.start();
});