Example usage for javafx.application Platform runLater

List of usage examples for javafx.application Platform runLater

Introduction

In this page you can find the example usage for javafx.application Platform runLater.

Prototype

public static void runLater(Runnable runnable) 

Source Link

Document

Run the specified Runnable on the JavaFX Application Thread at some unspecified time in the future.

Usage

From source file:com.eby.admin.register.RegisterForAdminController.java

/**
 * Initializes the controller class.//from   w w  w  . ja  v a 2s .c o  m
 *
 * @param url
 * @param rb
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    initModel();
    addcbLvl();
    con = new Config();
    fadeIn();
    //dijalankan apabila hanya diperlukan
    Platform.runLater(() -> {
        txtEmail.setOnKeyReleased((KeyEvent event) -> {
            validdator = EmailValidator.getInstance(true);
            if (validdator.isValid(txtEmail.getText())) {
                //jika email valid, css class menjadi valid-label
                labelValid.getStyleClass().remove("invalid-label");
                labelValid.getStyleClass().add("valid-label");
            } else {
                //jika email invalid, css class menjadi invalid-label
                labelValid.getStyleClass().remove("valid-label");
                labelValid.getStyleClass().add("invalid-label");
            }
        });
    });
    //txtNotif nonaktif
    txtNotif.setVisible(false);

}

From source file:com.cooksys.httpserver.IncomingHttpHandler.java

@Override
public void handle(final HttpRequest request, final HttpResponse response, HttpContext context)
        throws HttpException, IOException {
    //put the entity stream into a string - sending this object to JavaFX runlater
    //queue causes the stream to close, so we will have to do it here
    final String messageBody;
    if (request instanceof BasicHttpEntityEnclosingRequest) {
        HttpEntity entity = ((BasicHttpEntityEnclosingRequest) request).getEntity();
        if (entity.getContentLength() < Integer.MAX_VALUE / 2) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            entity.writeTo(stream);//from  www  . j  av a2s  .  c o  m
            messageBody = stream.toString();
        } else {
            messageBody = "Data too large";
        }
    } else {
        messageBody = "";
    }

    //Print the raw request message to the message console
    rawMessage = "\n\n";
    rawMessage += request.getRequestLine().toString() + "\n";

    Header[] headers = request.getAllHeaders();
    for (Header header : headers) {
        rawMessage += header.getName() + ": " + header.getValue() + "\n";
    }
    rawMessage += "\n";
    rawMessage += messageBody;

    //get the default response from the model, and copy it to the already provided HttpResponse parameter
    HttpResponse defaultResponse = serverModel.getResponseList().get(serverModel.getDefaultResponseIndex())
            .encodeResponse();

    response.setStatusLine(defaultResponse.getStatusLine());
    response.setEntity(defaultResponse.getEntity());
    response.setHeaders(defaultResponse.getAllHeaders());

    System.out.println("sending response -> " + response.toString());
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            //update the model with the console message
            String originalConsole = serverModel.getMessageConsole().getValue();
            serverModel.getMessageConsole()
                    .set(originalConsole == null ? rawMessage : originalConsole + rawMessage);
        }
    });

    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            //update the model with the new message
            serverModel.incomingRequest(request, messageBody);
        }
    });
    System.out.println("handle() end");
}

From source file:pah9qdmoviereviews.MovieReviewsFXMLController.java

public void ready(Stage stage, Scene scene) {
    this.stage = stage;
    this.scene = scene;

    movieReviewManager = new NYTMoviewReviewManager();
    movieReviewManager.addPropertyChangeSupport(((evt) -> {
        switch (evt.getPropertyName()) {
        case "Exception":
            Platform.runLater(() -> displayExceptionAlert((Exception) evt.getNewValue()));
            break;
        case "Add Movie Review":
            Platform.runLater(() -> {
                movieReviews.add((NYTMovieReview) evt.getNewValue());
                this.foundText.setText(("Found " + movieReviews.size() + " results for " + searchString + "."));
            });//from  ww w. j a v  a 2 s  . c o m
            break;
        case "Clear Movie Reviews":
            Platform.runLater(() -> movieReviews.clear());
            break;
        case "Completed":
            if (movieReviews.isEmpty())
                this.foundText.setText("No reviews found for " + searchString);
            break;
        default:
            Platform.runLater(
                    () -> displayExceptionAlert(new Exception("Invalid Property Change Support Property")));
            break;
        }

    }));

    movieReviews = FXCollections.observableArrayList();
    listView.setItems(movieReviews);
    listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<NYTMovieReview>() {
        @Override
        public void changed(ObservableValue<? extends NYTMovieReview> observable, NYTMovieReview oldValue,
                NYTMovieReview newValue) {
            detailsBox.getChildren().clear();
            movieImage.setImage(null);
            if (newValue != null) {
                DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
                String pictureLink = newValue.getPictureLink();
                if (pictureLink != null && !pictureLink.isEmpty()) {
                    reviewBox.getChildren().remove(0);
                    reviewBox.getChildren().add(0, movieImage);
                    movieImage.setImage(new Image(pictureLink));
                } else {
                    reviewBox.getChildren().remove(0);
                    reviewBox.getChildren().add(0, missingImageText);
                    movieImage.setImage(null);
                }

                ArrayList<Label> labelArray = new ArrayList<>();
                if (!newValue.getDisplayTitle().isEmpty()) {
                    Label titleLabel = new Label(newValue.getDisplayTitle());
                    titleLabel.fontProperty().set(Font.font(20));
                    labelArray.add(titleLabel);
                }
                if (!newValue.getSummary().isEmpty()) {
                    labelArray.add(new Label("Summary: " + newValue.getSummary()));
                }
                if (!newValue.getMpaaRating().isEmpty()) {
                    labelArray.add(new Label("MPAA Rating: " + newValue.getMpaaRating()));
                }
                if (newValue.getPublicationDate() != null) {
                    labelArray.add(
                            new Label("Publication Date: " + dateFormat.format(newValue.getPublicationDate())));
                }
                if (newValue.getOpeningDate() != null) {
                    labelArray.add(new Label("Opening Date: " + dateFormat.format(newValue.getOpeningDate())));
                }

                labelArray.forEach((label) -> {
                    label.wrapTextProperty().set(true);
                });

                detailsBox.getChildren().addAll(labelArray);

                Button openButton = new Button("Open Review");
                openButton.setOnAction((event) -> {
                    try {
                        Desktop.getDesktop().browse(new URI(newValue.getArticleLink()));
                    } catch (Exception ex) {
                        displayExceptionAlert(ex);
                    }
                });

                detailsBox.getChildren().add(openButton);
            }
        }
    });

    HBox.setMargin(missingImageText, new Insets(15, 15, 15, 15));
    searchTextField.setOnKeyPressed((event) -> {
        if (event.getCode() == KeyCode.ENTER) {
            loadReviews(searchTextField.getText());
        }
    });
    //        searchTextField.textProperty().addListener((observable, oldValue, newValue) -> {
    //            if(newValue != null && !newValue.isEmpty())
    //                loadReviews(newValue);
    //        });
}

From source file:com.properned.model.MultiLanguageProperties.java

private void init() {
    Platform.runLater(new Runnable() {
        @Override/*from w w  w  . j av a2s  .  co m*/
        public void run() {
            logger.info("Initializing the multi language properties instance");
            isDirty.set(false);
            isLoaded.set(false);
            mapPropertiesByLocale.clear();
            mapPropertiesFileByLocale.clear();
            listMessageKey.clear();
        }
    });
}

From source file:herudi.controller.microMarketController.java

/**
 * Initializes the controller class./*from   www. j a  v a 2 s .c o  m*/
 * @param url
 * @param rb
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    Platform.runLater(() -> {
        ApplicationContext ctx = config.getInstance().getApplicationContext();
        crud = ctx.getBean(interMicro.class);
        listData = FXCollections.observableArrayList();
        status = 0;
        config2.setModelColumn(colAreaLength, "areaLength");
        config2.setModelColumn(colAreaWidth, "areaWidth");
        config2.setModelColumn(colRadius, "radius");
        config2.setModelColumn(colZip, "zipCode");
        colAction.setCellValueFactory(
                new Callback<TableColumn.CellDataFeatures<Object, Boolean>, ObservableValue<Boolean>>() {
                    @Override
                    public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<Object, Boolean> p) {
                        return new SimpleBooleanProperty(p.getValue() != null);
                    }
                });
        colAction.setCellFactory(new Callback<TableColumn<Object, Boolean>, TableCell<Object, Boolean>>() {
            @Override
            public TableCell<Object, Boolean> call(TableColumn<Object, Boolean> p) {
                return new ButtonCell(tableData);
            }
        });
        selectWithService();
    });
    // TODO
}

From source file:deincraftlauncher.start.StartMinecraft.java

public static void startMC(Modpack pack) {

    try {//from w  ww  .ja v a2s . c  o m

        System.out.println("trying to start minecraft");

        GameInfos infos = new GameInfos(pack.getName(), new File(pack.getPath()),
                new GameVersion(pack.getMCVersion(), pack.getGameType()), new GameTweak[] { GameTweak.FORGE });
        System.out.println("GameInfos done");

        System.out.println("Zugangsdaten: " + settings.getUsername() + settings.getPassword());

        Authenticator authenticator = new Authenticator(Authenticator.MOJANG_AUTH_URL,
                AuthPoints.NORMAL_AUTH_POINTS);
        AuthResponse rep = authenticator.authenticate(AuthAgent.MINECRAFT, settings.getUsername(),
                settings.getPassword(), "");
        AuthInfos authInfos = new AuthInfos(rep.getSelectedProfile().getName(), rep.getAccessToken(),
                rep.getSelectedProfile().getId());
        System.out.println("authinfos done");

        //AuthInfos authInfos = new AuthInfos(settings.getUsername(), MCAuthentication.getToken(settings.getUsername(), settings.getPassword()), MCAuthentication.getUUID(settings.getUsername(), settings.getPassword()));

        ExternalLaunchProfile profile = MinecraftLauncher.createExternalProfile(infos, getFolder(pack),
                authInfos);
        List<String> vmArgs = profile.getVmArgs();
        vmArgs.add(String.valueOf("-Xms" + settings.getRAM() + "m"));
        //System.out.println("vm args: " + vmArgs);
        profile.setVmArgs(vmArgs);
        ExternalLauncher launcher = new MCLauncher(profile);
        System.out.println("profile and launcher done " + launcher.getProfile());

        Process launch = launcher.launch();

        BufferedReader stdout = new BufferedReader(new InputStreamReader(launch.getInputStream()));
        String line;

        while ((line = stdout.readLine()) != null) {
            System.out.println(line);
        }
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Platform.runLater(() -> {
                    System.out.println("minecraft started, changing start state");
                    pack.setStartState(PackViewHandler.StartState.Loading);
                    pack.setStartText("gestartet");
                });
            }
        }, 8000);

        checkAlive(launch, pack);

    } catch (LaunchException | AuthenticationException | IOException ex) {
        Logger.getLogger(StartMinecraft.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:Dominion.DynamicCard.ClientModelService.java

@Override
public synchronized void handle(String json_stringified) {
    JSONObject obj = JSonFactory.JSON.toJSON(json_stringified);
    String action = obj.getString("act");
    switch (action) {
    case ("gain"): {
        String cardname = obj.getString("gain");
        final Card c = new Card(cardname, controller);
        currentHand.add(c);//from  ww w .  ja  va 2 s .  com
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                controller.addCardToHand(c.getView());
            }
        });
        break;
    }
    case ("lose"): {
        final String cardname = obj.getString("lose");
        final Long id = Long.valueOf(obj.getString("loseID"));
        // Current implementation: Lose the first card with the same cardname. 
        // Later implemantation: Lose the exact card that you selected
        //                  You can verify this by checking the ID of the clicked card
        if (cardname.equals("all")) {
            currentHand.clear();
            Platform.runLater(new Runnable() {

                @Override
                public void run() {
                    controller.refreshHandView();
                }

            });

            break;
        }

        ArrayList<Card> nextHand = new ArrayList<>();
        boolean extracted = false;
        for (Card c : currentHand) {
            if (!extracted) {
                if (c.getName().equals(cardname) && c.getID().equals(id)) {
                    extracted = true;
                    continue;
                }
            }
            nextHand.add(c);
        }
        currentHand = nextHand;

        // Now lose all cards, and one by one add the remaining cards.
        Platform.runLater(new Runnable() {

            @Override
            public void run() {
                controller.refreshHandView();
                for (Card c : currentHand) {
                    controller.addCardToHand(c.getView());
                }
            }

        });
        break;
    }
    case ("control"): {
        // Do some other shit
        handleControlPackage(obj);
        break;
    }
    case ("turninfo"): {
        // Turninfo update
        updateTurnInfo(obj);
        break;
    }
    case ("confirm"): {
        // Confirmation
        handleConfirmationPackage(obj);
        break;
    }
    case ("confirm_end"): {
        // Confirmation confirmed
        confirmationmanager.hide();
        break;
    }
    default: {
        System.err.println("Action not defined in clientmodelservice: [" + action + "].");
    }
    }
}

From source file:com.panemu.tiwulfx.control.skin.LookupFieldSkin.java

public LookupFieldSkin(LookupField<T> control) {
    super(control, new LookupFieldBehavior<>(control));
    this.lookupField = control;
    // move focus in to the textfield
    lookupField.focusedProperty().addListener(new ChangeListener<Boolean>() {
        @Override// w  ww  .  j  ava 2 s  .  co  m
        public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean hasFocus) {
            if (hasFocus) {
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        textField.requestFocus();
                    }
                });
            }

        }
    });
    initialize();

    textField.focusedProperty().addListener(new ChangeListener<Boolean>() {

        @Override
        public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean hasFocus) {
            if (!hasFocus) {
                validate();
            }
        }
    });

    lookupField.addEventFilter(InputEvent.ANY, new EventHandler<InputEvent>() {
        @Override
        public void handle(InputEvent t) {
            if (textField == null) {
                return;
            }

            // When the user hits the enter or F4 keys, we respond before 
            // ever giving the event to the TextField.
            if (t instanceof KeyEvent) {
                KeyEvent ke = (KeyEvent) t;

                if ((ke.getCode() == KeyCode.F10 || ke.getCode() == KeyCode.ESCAPE
                        || ke.getCode() == KeyCode.ENTER) && !ke.isControlDown()) {

                    // RT-23275: The TextField fires F10 and ESCAPE key events
                    // up to the parent, which are then fired back at the 
                    // TextField, and this ends up in an infinite loop until
                    // the stack overflows. So, here we consume these two
                    // events and stop them from going any further.
                    t.consume();
                    return;
                }
            }
        }
    });

    textField.promptTextProperty().bind(lookupField.promptTextProperty());
    getSkinnable().requestLayout();

    registerChangeListener(control.showingSuggestionProperty(), PROP_SHOWING_SUGGESTION);
    registerChangeListener(control.showingLookupDialogProperty(), PROP_SHOWING_LOOKUP_WINDOW);
    registerChangeListener(control.resettingDisplayTextProperty(), PROP_RESETTING_DISPLAY_TEXT);
}

From source file:org.sleuthkit.autopsy.imagegallery.gui.navpanel.GroupTreeCell.java

public GroupTreeCell() {
    getStylesheets().add(GroupTreeCell.class.getResource("GroupTreeCell.css").toExternalForm());
    getStyleClass().add("groupTreeCell"); //reduce  indent to 5, default is 10 which uses up a lot of space.

    //since end of path is probably more interesting put ellipsis at front
    setTextOverrun(OverrunStyle.LEADING_ELLIPSIS);
    Platform.runLater(() -> {
        prefWidthProperty().bind(getTreeView().widthProperty().subtract(15));
    });/*from ww  w. ja v  a2  s .com*/

}

From source file:dpfmanager.shell.core.util.TextAreaAppender.java

@Override
public void append(LogEvent event) {
    if (textArea != null) {
        Layout layout = this.getLayout();
        Platform.runLater(new Runnable() {
            @Override//from   w  w w  .  j  av  a 2  s  . c om
            public void run() {
                String message = new String(layout.toByteArray(event));
                int count = StringUtils.countMatches(textArea.getText(), "\n");
                if (count < maxLines && maxLines != 0) {
                    textArea.appendText(message);
                } else {
                    textArea.clear();
                    textArea.autosize();
                    textArea.appendText(message);
                }
            }
        });
    }

}