Example usage for javafx.concurrent Service Service

List of usage examples for javafx.concurrent Service Service

Introduction

In this page you can find the example usage for javafx.concurrent Service Service.

Prototype

protected Service() 

Source Link

Document

Create a new Service.

Usage

From source file:herudi.controller.customerController.java

private void selectWithService() {
    Service<Integer> service = new Service<Integer>() {
        @Override// www .ja  va  2  s  .c  o m
        protected Task<Integer> createTask() {
            selectData();
            return new Task<Integer>() {
                @Override
                protected Integer call() throws Exception {
                    Integer max = crud.select().size();
                    if (max > 35) {
                        max = 30;
                    }
                    updateProgress(0, max);
                    for (int k = 0; k < max; k++) {
                        Thread.sleep(40);
                        updateProgress(k + 1, max);
                    }
                    return max;
                }
            };
        }
    };
    service.start();
    bar.progressProperty().bind(service.progressProperty());
    service.setOnRunning((WorkerStateEvent event) -> {
        imgLoad.setVisible(true);
    });
    service.setOnSucceeded((WorkerStateEvent event) -> {
        imgLoad.setVisible(false);
        new FadeInUpTransition(paneTabel).play();
    });
}

From source file:com.jscriptive.moneyfx.ui.chart.ChartFrame.java

/**
 * This method is invoked when the monthly in/out button has been toggled
 *
 * @param actionEvent/* www. ja v a 2  s. co m*/
 */
public void monthlyInOutToggled(ActionEvent actionEvent) {
    final CategoryAxis xAxis = new CategoryAxis();
    final NumberAxis yAxis = new NumberAxis();
    xAxis.setLabel("Month of Year");
    yAxis.setLabel("In/Out in Euro");

    final BarChart<String, Number> barChart = new BarChart<>(xAxis, yAxis);
    barChart.setTitle("Monthly in/out");

    chartFrame.setCenter(barChart);

    ToggleButton toggle = (ToggleButton) actionEvent.getTarget();
    if (toggle.isSelected()) {
        Account account = accountCombo.getValue();
        String accountLabel = getAccountLabel(account);

        XYChart.Series<String, Number> inSeries = new XYChart.Series<>();
        inSeries.setName("In" + accountLabel);
        barChart.getData().add(inSeries);

        XYChart.Series<String, Number> outSeries = new XYChart.Series<>();
        outSeries.setName("Out" + accountLabel);
        barChart.getData().add(outSeries);

        ValueRange<LocalDate> period = getTransactionOpRange(account, yearCombo.getValue());
        if (period.isEmpty()) {
            return;
        }
        ObservableList<String> monthLabels = FXCollections.observableArrayList();
        for (LocalDate date = period.from().withDayOfMonth(1); !date.isAfter(period.to()); date = date
                .plusMonths(1)) {
            monthLabels.add(getMonthLabel(date.getYear(), date.getMonthValue()));
        }
        xAxis.setCategories(monthLabels);
        Service<Void> service = new Service<Void>() {
            @Override
            protected Task<Void> createTask() {
                return new Task<Void>() {
                    @Override
                    protected Void call() throws Exception {

                        List<TransactionVolume> incomingVolumes = (account == ALL_ACCOUNTS)
                                ? transactionRepository.getMonthlyIncomingVolumes(false)
                                : transactionRepository.getMonthlyIncomingVolumesOfAccount(account, false);
                        if (INTEGER_ZERO.compareTo(yearCombo.getValue()) < 0) {
                            incomingVolumes = incomingVolumes.stream()
                                    .filter(v -> v.getYear().equals(yearCombo.getValue()))
                                    .sorted((v1, v2) -> v1.getDate().compareTo(v2.getDate())).collect(toList());
                        }
                        for (TransactionVolume volume : incomingVolumes) {
                            String monthLabel = getMonthLabel(volume.getYear(), volume.getMonth());
                            XYChart.Data<String, Number> data = new XYChart.Data<>(monthLabel,
                                    volume.getVolume());
                            Platform.runLater(() -> {
                                inSeries.getData().add(data);
                                StackPane barNode = (StackPane) data.getNode();
                                // TODO make that look nicer
                                Label labelNode = new Label(
                                        CurrencyFormat.getInstance().format(volume.getVolume()));
                                labelNode.setPrefWidth(100);
                                labelNode.setAlignment(CENTER_RIGHT);
                                labelNode.setRotate(270);
                                barNode.getChildren().add(labelNode);
                                barNode.addEventHandler(MOUSE_CLICKED,
                                        event -> handleMonthlyInOutChartMouseClickEvent(
                                                (account == ALL_ACCOUNTS) ? null : account,
                                                of(volume.getYear(), volume.getMonth(), 1), event));
                            });
                        }

                        List<TransactionVolume> outgoingVolumes = (account == ALL_ACCOUNTS)
                                ? transactionRepository.getMonthlyOutgoingVolumes(false)
                                : transactionRepository.getMonthlyOutgoingVolumesOfAccount(account, false);
                        if (INTEGER_ZERO.compareTo(yearCombo.getValue()) < 0) {
                            outgoingVolumes = outgoingVolumes.stream()
                                    .filter(v -> v.getYear().equals(yearCombo.getValue()))
                                    .sorted((v1, v2) -> v1.getDate().compareTo(v2.getDate())).collect(toList());
                        }
                        for (TransactionVolume volume : outgoingVolumes) {
                            String monthLabel = getMonthLabel(volume.getYear(), volume.getMonth());
                            XYChart.Data<String, Number> data = new XYChart.Data<>(monthLabel,
                                    volume.getVolume().abs());
                            Platform.runLater(() -> {
                                outSeries.getData().add(data);
                                StackPane node = (StackPane) data.getNode();
                                // TODO make that look nicer
                                Label labelNode = new Label(
                                        CurrencyFormat.getInstance().format(volume.getVolume()));
                                labelNode.setPrefWidth(100);
                                labelNode.setAlignment(CENTER_RIGHT);
                                labelNode.setRotate(270);
                                node.getChildren().add(labelNode);
                                node.addEventHandler(MOUSE_CLICKED,
                                        event -> handleMonthlyInOutChartMouseClickEvent(
                                                (account == ALL_ACCOUNTS ? null : account), volume.getDate(),
                                                event));
                            });
                        }

                        return null;
                    }
                };
            }
        };
        service.start();
    }
}

From source file:com.jscriptive.moneyfx.ui.chart.ChartFrame.java

public void yearlyInOutToggled(ActionEvent actionEvent) {
    final NumberAxis xAxis = new NumberAxis();
    final CategoryAxis yAxis = new CategoryAxis();
    yAxis.setLabel("In/Out in Euro");
    xAxis.setLabel("Year");

    final BarChart<Number, String> barChart = new BarChart<>(xAxis, yAxis);
    barChart.setTitle("Yearly in/out");

    chartFrame.setCenter(barChart);/*from w ww .j av  a 2 s  .c  o m*/

    ToggleButton toggle = (ToggleButton) actionEvent.getTarget();
    if (toggle.isSelected()) {
        Account account = accountCombo.getValue();
        String accountLabel = getAccountLabel(account);

        XYChart.Series<Number, String> inSeries = new XYChart.Series<>();
        inSeries.setName("In" + accountLabel);
        barChart.getData().add(inSeries);

        XYChart.Series<Number, String> outSeries = new XYChart.Series<>();
        outSeries.setName("Out" + accountLabel);
        barChart.getData().add(outSeries);

        ValueRange<LocalDate> period = getTransactionOpRange(account, yearCombo.getValue());
        if (period.isEmpty()) {
            return;
        }
        ObservableList<String> categories = FXCollections.observableArrayList();
        for (int y = period.from().getYear(); y < period.to().getYear() + 6; y++) {
            categories.add(String.valueOf(y));
        }
        yAxis.setCategories(categories);
        Service<Void> service = new Service<Void>() {
            @Override
            protected Task<Void> createTask() {
                return new Task<Void>() {
                    @Override
                    protected Void call() throws Exception {

                        List<TransactionVolume> incomingVolumes = (account == ALL_ACCOUNTS)
                                ? transactionRepository.getYearlyIncomingVolumes(false)
                                : transactionRepository.getYearlyIncomingVolumesOfAccount(account, false);
                        if (INTEGER_ZERO.compareTo(yearCombo.getValue()) < 0) {
                            incomingVolumes = incomingVolumes.stream()
                                    .filter(v -> v.getYear().equals(yearCombo.getValue()))
                                    .sorted((v1, v2) -> v1.getDate().compareTo(v2.getDate())).collect(toList());
                        }
                        for (TransactionVolume volume : incomingVolumes) {
                            XYChart.Data<Number, String> inData = new XYChart.Data<>(volume.getVolume(),
                                    String.valueOf(volume.getYear()));
                            Platform.runLater(() -> {
                                inSeries.getData().add(inData);
                                StackPane node = (StackPane) inData.getNode();
                                node.getChildren().add(
                                        new Label(CurrencyFormat.getInstance().format(volume.getVolume())));
                                node.addEventHandler(MOUSE_CLICKED,
                                        event -> handleYearlyInOutChartMouseClickEvent(
                                                (account == ALL_ACCOUNTS) ? null : account,
                                                ofYearDay(volume.getYear(), 1), event));
                            });
                        }

                        List<TransactionVolume> outgoingVolumes = (account == ALL_ACCOUNTS)
                                ? transactionRepository.getYearlyOutgoingVolumes(false)
                                : transactionRepository.getYearlyOutgoingVolumesOfAccount(account, false);
                        if (INTEGER_ZERO.compareTo(yearCombo.getValue()) < 0) {
                            outgoingVolumes = outgoingVolumes.stream()
                                    .filter(v -> v.getYear().equals(yearCombo.getValue()))
                                    .sorted((v1, v2) -> v1.getDate().compareTo(v2.getDate())).collect(toList());
                        }
                        for (TransactionVolume volume : outgoingVolumes) {
                            XYChart.Data<Number, String> outData = new XYChart.Data<>(volume.getVolume().abs(),
                                    String.valueOf(volume.getYear()));
                            Platform.runLater(() -> {
                                outSeries.getData().add(outData);
                                StackPane node = (StackPane) outData.getNode();
                                node.getChildren().add(
                                        new Label(CurrencyFormat.getInstance().format(volume.getVolume())));
                                node.addEventHandler(MOUSE_CLICKED,
                                        event -> handleYearlyInOutChartMouseClickEvent(
                                                (account == ALL_ACCOUNTS) ? null : account,
                                                ofYearDay(volume.getYear(), 1), event));
                            });
                        }

                        return null;
                    }
                };
            }
        };
        service.start();

    }
}

From source file:com.jscriptive.moneyfx.ui.chart.ChartFrame.java

/**
 * This method is invoked when the "by category" button has been toggled
 *
 * @param actionEvent/* w ww.  ja v  a  2  s.  co  m*/
 */
public void byCategoryToggled(ActionEvent actionEvent) {
    final PieChart pieChart = new PieChart();
    pieChart.setTitle("Transaction balance by categories");
    pieChart.setLegendSide(LEFT);
    chartFrame.setCenter(pieChart);
    ToggleButton toggle = (ToggleButton) actionEvent.getTarget();
    if (toggle.isSelected()) {
        Service<Void> service = new Service<Void>() {
            @Override
            protected Task<Void> createTask() {
                return new Task<Void>() {
                    @Override
                    protected Void call() throws Exception {
                        ValueRange<LocalDate> period = getTransactionOpRange(accountCombo.getValue(),
                                yearCombo.getValue());
                        if (period.isEmpty()) {
                            return null;
                        }
                        Platform.runLater(() -> pieChart.setTitle(format("%s for transactions from %s until %s",
                                pieChart.getTitle(), period.from().format(DATE_FORMATTER),
                                period.to().format(DATE_FORMATTER))));

                        categoryRepository.findAll().stream()
                                .sorted((c1, c2) -> c1.getName().compareTo(c2.getName())).forEach(category -> {
                                    List<Transaction> found = (accountCombo.getValue() == ALL_ACCOUNTS)
                                            ? transactionRepository.findByCategory(category)
                                            : transactionRepository.findByAccountAndCategory(
                                                    accountCombo.getValue(), category);
                                    if (INTEGER_ZERO.compareTo(yearCombo.getValue()) < 0) {
                                        found = found.stream().filter(
                                                trx -> yearCombo.getValue().equals(trx.getDtOp().getYear()))
                                                .sorted((t1, t2) -> t1.getDtOp().compareTo(t2.getDtOp()))
                                                .collect(toList());
                                    }
                                    List<Transaction> transactions = new ArrayList<>(found.size());
                                    transactions.addAll(found);
                                    Platform.runLater(() -> {
                                        double value = getSum(transactions);
                                        String name = format("%s [%s]", category.getName(),
                                                CurrencyFormat.getInstance().format(value));
                                        PieChart.Data data = new PieChart.Data(name, value);
                                        pieChart.getData().add(data);
                                        data.getNode().addEventHandler(MOUSE_CLICKED,
                                                event -> handleCategoryChartMouseClickEvent(
                                                        (accountCombo.getValue() == ALL_ACCOUNTS) ? null
                                                                : accountCombo.getValue(),
                                                        category, yearCombo.getValue(), event));
                                    });
                                });
                        return null;
                    }
                };
            }
        };
        service.start();
    }
}

From source file:fr.amap.lidar.amapvox.gui.MainFrameController.java

private void getBoundingBoxOfPoints(final boolean quick) {

    if (textFieldInputFileALS.getText().equals("") && !removeWarnings) {

        Alert alert = new Alert(AlertType.INFORMATION);
        alert.setTitle("Information");
        alert.setHeaderText("An ALS file has to be open");
        alert.setContentText("An ALS file has to be open.\nTo proceed select ALS tab and choose a *.las file.");

        alert.showAndWait();//from   w  ww . j  ava2 s. c  o m

    } else {
        File file = new File(textFieldInputFileALS.getText());

        if (!Files.exists(file.toPath(), LinkOption.NOFOLLOW_LINKS)) {

            Alert alert = new Alert(AlertType.INFORMATION);
            alert.setTitle("Error");
            alert.setHeaderText("File not found");
            alert.setContentText("The file " + file.getAbsolutePath() + " cannot be found.");

            alert.showAndWait();

        } else if (FileManager.getExtension(file).equals(".las")
                || FileManager.getExtension(file).equals(".laz")) {

            Matrix4d identityMatrix = new Matrix4d();
            identityMatrix.setIdentity();

            ProgressDialog d;

            Service<Void> service = new Service<Void>() {

                @Override
                protected Task<Void> createTask() {

                    return new Task<Void>() {
                        @Override
                        protected Void call() throws InterruptedException {

                            final BoundingBox3d boundingBox = fr.amap.lidar.amapvox.util.Util
                                    .getBoundingBoxOfPoints(new File(textFieldInputFileALS.getText()),
                                            resultMatrix, quick, getListOfClassificationPointToDiscard());

                            Point3d minPoint = boundingBox.min;
                            Point3d maxPoint = boundingBox.max;

                            Platform.runLater(new Runnable() {

                                @Override
                                public void run() {
                                    voxelSpacePanelVoxelizationController.getTextFieldEnterXMin()
                                            .setText(String.valueOf(minPoint.x));
                                    voxelSpacePanelVoxelizationController.getTextFieldEnterYMin()
                                            .setText(String.valueOf(minPoint.y));
                                    voxelSpacePanelVoxelizationController.getTextFieldEnterZMin()
                                            .setText(String.valueOf(minPoint.z));

                                    voxelSpacePanelVoxelizationController.getTextFieldEnterXMax()
                                            .setText(String.valueOf(maxPoint.x));
                                    voxelSpacePanelVoxelizationController.getTextFieldEnterYMax()
                                            .setText(String.valueOf(maxPoint.y));
                                    voxelSpacePanelVoxelizationController.getTextFieldEnterZMax()
                                            .setText(String.valueOf(maxPoint.z));
                                }
                            });

                            return null;
                        }
                    };

                };
            };

            d = new ProgressDialog(service);
            d.initOwner(stage);
            d.setHeaderText("Please wait...");
            d.setResizable(true);

            d.show();

            service.start();

        }
    }
}

From source file:fr.amap.lidar.amapvox.gui.MainFrameController.java

@FXML
private void onActionButtonGetBoundingBox(ActionEvent event) {

    Mat4D vopMatrixTmp = MatrixUtility.convertMatrix4dToMat4D(vopMatrix);
    if (vopMatrixTmp == null && checkboxUseVopMatrix.isSelected()) {
        vopMatrixTmp = Mat4D.identity();
    }/*from  w  w  w.j  a  v  a 2  s  .c o  m*/

    final Mat4D transfMatrix = vopMatrixTmp;

    ObservableList<Node> children = vBoxPointCloudFiltering.getChildren();

    final List<PointCloudFilterPaneComponent> tempList = new ArrayList<>();

    for (Node n : children) {
        if (n instanceof PointCloudFilterPaneComponent) {

            PointCloudFilterPaneComponent comp = (PointCloudFilterPaneComponent) n;
            tempList.add(comp);
        }
    }

    Service<Void> service = new Service<Void>() {
        @Override
        protected Task<Void> createTask() {
            return new Task<Void>() {
                @Override
                protected Void call() throws InterruptedException {

                    final BoundingBox3F boundingBox = new BoundingBox3F();

                    int count = 0;

                    for (PointCloudFilterPaneComponent pane : tempList) {

                        if (pane.getComboboxPointCloudFilteringType().getSelectionModel()
                                .getSelectedIndex() == 0) {

                            CSVFile file = pane.getCsvFile();

                            if (Files.exists(file.toPath()) && file.isFile()) {

                                PointCloud pc = new PointCloud();
                                try {
                                    pc.readFromFile(file, transfMatrix);
                                } catch (IOException ex) {

                                }

                                BoundingBox3F boundingBox2;
                                if (count == 0) {
                                    boundingBox2 = pc.getBoundingBox();
                                    boundingBox.min = boundingBox2.min;
                                    boundingBox.max = boundingBox2.max;

                                } else {
                                    boundingBox2 = pc.getBoundingBox();
                                    boundingBox.keepLargest(boundingBox2);
                                }
                                count++;
                            }
                        }
                    }

                    Platform.runLater(new Runnable() {

                        @Override
                        public void run() {
                            Alert alert = new Alert(AlertType.CONFIRMATION);
                            alert.setTitle("Information");
                            alert.setHeaderText("Bounding box:");
                            alert.setContentText("Minimum: " + "x: " + boundingBox.min.x + " y: "
                                    + boundingBox.min.y + " z: " + boundingBox.min.z + "\n" + "Maximum: "
                                    + "x: " + boundingBox.max.x + " y: " + boundingBox.max.y + " z: "
                                    + boundingBox.max.z + "\n\n" + "Use for voxel space bounding-box?");

                            alert.initModality(Modality.NONE);
                            Optional<ButtonType> answer = alert.showAndWait();
                            if (answer.get() == ButtonType.OK) {

                                voxelSpacePanelVoxelizationController.getTextFieldEnterXMin()
                                        .setText(String.valueOf(boundingBox.min.x));
                                voxelSpacePanelVoxelizationController.getTextFieldEnterYMin()
                                        .setText(String.valueOf(boundingBox.min.y));
                                voxelSpacePanelVoxelizationController.getTextFieldEnterZMin()
                                        .setText(String.valueOf(boundingBox.min.z));

                                voxelSpacePanelVoxelizationController.getTextFieldEnterXMax()
                                        .setText(String.valueOf(boundingBox.max.x));
                                voxelSpacePanelVoxelizationController.getTextFieldEnterYMax()
                                        .setText(String.valueOf(boundingBox.max.y));
                                voxelSpacePanelVoxelizationController.getTextFieldEnterZMax()
                                        .setText(String.valueOf(boundingBox.max.z));
                            }
                        }
                    });

                    return null;
                }
            };
        }
    };

    ProgressDialog d = new ProgressDialog(service);
    d.initOwner(stage);
    d.show();

    service.start();

}

From source file:fr.amap.lidar.amapvox.gui.MainFrameController.java

private void exportDartPlots(final File voxelFile) {

    if (Util.checkIfVoxelFile(voxelFile)) {

        fileChooserSaveDartFile.setInitialFileName("plots.xml");
        fileChooserSaveDartFile.setInitialDirectory(voxelFile.getParentFile());

        final File plotFile = fileChooserSaveDartFile.showSaveDialog(stage);

        if (plotFile != null) {

            Alert alert = new Alert(AlertType.CONFIRMATION);

            alert.setTitle("Coordinate system");
            alert.setContentText("Choose your coordinate system");

            ButtonType buttonTypeGlobal = new ButtonType("Global");
            ButtonType buttonTypeLocal = new ButtonType("Local");

            alert.getButtonTypes().setAll(buttonTypeGlobal, buttonTypeLocal);

            Optional<ButtonType> result = alert.showAndWait();

            final boolean global;

            if (result.get() == buttonTypeGlobal) {
                global = true;//from w w w.ja va 2 s. c  om
            } else if (result.get() == buttonTypeLocal) {
                global = false;
            } else {
                return;
            }

            final DartPlotsXMLWriter dartPlotsXML = new DartPlotsXMLWriter();

            final Service service = new Service() {

                @Override
                protected Task createTask() {
                    return new Task<Object>() {

                        @Override
                        protected Object call() throws Exception {

                            dartPlotsXML.writeFromVoxelFile(voxelFile, plotFile, global);
                            return null;
                        }
                    };
                }
            };

            ProgressDialog progressDialog = new ProgressDialog(service);
            progressDialog.show();
            service.start();

            Button buttonCancel = new Button("cancel");
            progressDialog.setGraphic(buttonCancel);

            buttonCancel.setOnAction(new EventHandler<ActionEvent>() {

                @Override
                public void handle(ActionEvent event) {
                    service.cancel();
                    dartPlotsXML.setCancelled(true);
                }
            });

        }
    } else {
        logger.error("File is not a voxel file: " + voxelFile.getAbsolutePath());
        Alert alert = new Alert(AlertType.CONFIRMATION);
        alert.setHeaderText("Incorrect file");
        alert.setContentText("File is corrupted or cannot be read!\n" + "Do you want to keep it?");

        Optional<ButtonType> result = alert.showAndWait();

        if (result.get() == ButtonType.CANCEL) {
            listViewProductsFiles.getItems().remove(voxelFile);
        }
    }

}

From source file:fr.amap.lidar.amapvox.gui.MainFrameController.java

private void editVoxelSpace(final File voxelFile) {

    if (editingFrameOpened) {
        return;/*w ww  . ja v  a 2  s  . c om*/
    }

    editingFrameOpened = true;
    voxelsToRemove.clear();

    final String attributeToView = "PadBVTotal";

    //window size
    ObservableList<Screen> screens = Screen.getScreens();

    if (screens != null && screens.size() > 0) {
        SCREEN_WIDTH = screens.get(0).getBounds().getWidth();
        SCREEN_HEIGHT = screens.get(0).getBounds().getHeight();
    }

    try {

        Service s = new Service() {

            @Override
            protected Task createTask() {
                return new Task() {

                    @Override
                    protected Object call() throws Exception {

                        SimpleViewer viewer3D = new SimpleViewer((int) (SCREEN_WIDTH / 4.0d),
                                (int) (SCREEN_HEIGHT / 4.0d), (int) (SCREEN_WIDTH / 1.5d),
                                (int) (SCREEN_HEIGHT / 2.0d), voxelFile.toString());

                        fr.amap.viewer3d.object.scene.Scene scene = viewer3D.getScene();

                        /**
                         * *VOXEL SPACE**
                         */
                        updateMessage("Loading voxel space: " + voxelFile.getAbsolutePath());

                        final VoxelSpaceSceneObject voxelSpace = new VoxelSpaceSceneObject(voxelFile);
                        voxelSpace.setMousePickable(true);

                        voxelSpace.addVoxelSpaceListener(new VoxelSpaceAdapter() {

                            @Override
                            public void voxelSpaceCreationProgress(int progress) {
                                updateProgress(progress, 100);
                            }
                        });

                        voxelSpace.loadVoxels();
                        float voxelResolution = voxelSpace.data.getVoxelSpaceInfos().getResolution();

                        VoxelFileReader reader = new VoxelFileReader(voxelFile);
                        VoxelSpaceInfos infos = reader.getVoxelSpaceInfos();

                        final SceneObject boundingBox = new SimpleSceneObject();
                        boundingBox.setMesh(GLMeshFactory.createBoundingBox((float) infos.getMinCorner().x,
                                (float) infos.getMinCorner().y, (float) infos.getMinCorner().z,
                                (float) infos.getMaxCorner().x, (float) infos.getMaxCorner().y,
                                (float) infos.getMaxCorner().z));

                        SimpleShader s = new SimpleShader();
                        s.setColor(new Vec3F(1, 0, 0));
                        boundingBox.setShader(s);
                        boundingBox.setDrawType(GLMesh.DrawType.LINES);
                        scene.addSceneObject(boundingBox);

                        /*
                         * Voxel information
                         */
                        StringToImage stringToImage = new StringToImage(1024, 1024);
                        stringToImage.setAdaptableFontSize(true);
                        stringToImage.setBackgroundColor(new Color(255, 255, 255, 127));
                        stringToImage.setTextColor(new Color(0, 0, 0, 255));

                        BufferedImage image = new BufferedImage(1024, 1024, BufferedImage.TYPE_INT_ARGB);

                        Texture texture = new Texture(image);

                        int pickingInfoObjectWidth = viewer3D.getWidth() / 5;
                        int pickingInfoObjectHeight = viewer3D.getHeight() / 5;

                        SceneObject pickingInfoObject = SceneObjectFactory.createTexturedPlane(
                                new Vec3F(viewer3D.getWidth() - pickingInfoObjectWidth,
                                        viewer3D.getHeight() - pickingInfoObjectHeight, 0),
                                pickingInfoObjectWidth, pickingInfoObjectHeight, texture);

                        pickingInfoObject.setShader(new TextureShader());
                        pickingInfoObject.setDrawType(GLMesh.DrawType.TRIANGLES);

                        SceneObject sceneObjectSelectedVox = new SimpleSceneObject(
                                GLMeshFactory.createBoundingBox(-voxelResolution / 2.0f,
                                        -voxelResolution / 2.0f, -voxelResolution / 2.0f,
                                        voxelResolution / 2.0f, voxelResolution / 2.0f, voxelResolution / 2.0f),
                                false);

                        SimpleShader simpleShader = new SimpleShader();
                        simpleShader.setColor(new Vec3F(1, 0, 0));
                        sceneObjectSelectedVox.setVisible(false);
                        sceneObjectSelectedVox.setShader(simpleShader);
                        sceneObjectSelectedVox.setDrawType(GLMesh.DrawType.LINES);

                        viewer3D.getScene().addSceneObject(sceneObjectSelectedVox);

                        final SimpleObjectProperty<VoxelObject> selectedVoxel = new SimpleObjectProperty<>();

                        SceneObjectListener listener = new SceneObjectListener() {
                            @Override
                            public void clicked(SceneObject sceneObject, MousePicker mousePicker,
                                    Point3D intersection) {

                                Vec3F camLocation = viewer3D.getScene().getCamera().getLocation();

                                selectedVoxel.set(voxelSpace.doPicking(mousePicker));

                                if (selectedVoxel.get() != null) {

                                    String[][] lines = new String[voxelSpace.getColumnsNames().length][2];

                                    for (int i = 0; i < voxelSpace.getColumnsNames().length; i++) {

                                        lines[i][0] = voxelSpace.getColumnsNames()[i];

                                        float attribut = selectedVoxel.get().getAttributs()[i];
                                        if (Float.isNaN(attribut)) {
                                            lines[i][1] = "NaN";
                                        } else {
                                            lines[i][1] = String
                                                    .valueOf(Math.round(attribut * 1000.0f) / 1000.0f);
                                        }

                                    }

                                    arrangeText(lines);

                                    String text = "";
                                    for (int i = 0; i < voxelSpace.getColumnsNames().length; i++) {

                                        String attribut = lines[i][0] + " " + lines[i][1];
                                        text += attribut + "\n";
                                    }

                                    stringToImage.setText(text, 0, 0);

                                    texture.setBufferedImage(stringToImage.buildImage());
                                    Point3f voxelPosition = voxelSpace.getVoxelPosition(selectedVoxel.get().$i,
                                            selectedVoxel.get().$j, selectedVoxel.get().$k);

                                    sceneObjectSelectedVox.setPosition(
                                            new Point3F(voxelPosition.x, voxelPosition.y, voxelPosition.z));
                                    sceneObjectSelectedVox.setVisible(true);
                                    pickingInfoObject.setVisible(true);
                                } else {
                                    sceneObjectSelectedVox.setVisible(false);
                                    pickingInfoObject.setVisible(false);
                                }
                            }
                        };

                        final SimpleIntegerProperty currentZCropIndex = new SimpleIntegerProperty(0);

                        viewer3D.addEventListener(new EventManager(null, new InputKeyListener()) {
                            @Override
                            public void updateEvents() {

                                if (this.keyboard.isKeyClicked(KeyEvent.VK_DELETE)) {
                                    if (selectedVoxel.get() != null) {
                                        selectedVoxel.get().setAlpha(0);
                                        selectedVoxel.get().isHidden = true;
                                        voxelSpace.updateVao();
                                        sceneObjectSelectedVox.setVisible(false);
                                        pickingInfoObject.setVisible(false);
                                        voxelsToRemove.add(new Point3i(selectedVoxel.get().$i,
                                                selectedVoxel.get().$j, selectedVoxel.get().$k));
                                    }
                                }
                            }
                        });

                        voxelSpace.addSceneObjectListener(listener);

                        voxelSpace.changeCurrentAttribut(attributeToView);
                        voxelSpace.setShader(new InstanceLightedShader());
                        voxelSpace.setDrawType(GLMesh.DrawType.TRIANGLES);
                        scene.addSceneObject(voxelSpace);

                        scene.addSceneObjectAsHud(pickingInfoObject);

                        /**
                         * *scale**
                         */
                        updateMessage("Generating scale");
                        final Texture scaleTexture = new Texture(ScaleGradient.createColorScaleBufferedImage(
                                voxelSpace.getGradient(), voxelSpace.getAttributValueMin(),
                                voxelSpace.getAttributValueMax(), viewer3D.getWidth() - 80,
                                (int) (viewer3D.getHeight() / 20), ScaleGradient.Orientation.HORIZONTAL, 5, 8));

                        SceneObject scalePlane = SceneObjectFactory.createTexturedPlane(new Vec3F(40, 20, 0),
                                (int) (viewer3D.getWidth() - 80), (int) (viewer3D.getHeight() / 20),
                                scaleTexture);

                        scalePlane.setShader(new TextureShader());
                        scalePlane.setDrawType(GLMesh.DrawType.TRIANGLES);
                        scene.addSceneObjectAsHud(scalePlane);

                        voxelSpace.addPropertyChangeListener("gradientUpdated", new PropertyChangeListener() {

                            @Override
                            public void propertyChange(PropertyChangeEvent evt) {

                                BufferedImage image = ScaleGradient.createColorScaleBufferedImage(
                                        voxelSpace.getGradient(), voxelSpace.getAttributValueMin(),
                                        voxelSpace.getAttributValueMax(), viewer3D.getWidth() - 80,
                                        (int) (viewer3D.getHeight() / 20), ScaleGradient.Orientation.HORIZONTAL,
                                        5, 8);

                                scaleTexture.setBufferedImage(image);
                            }
                        });

                        /**
                         * *light**
                         */
                        scene.setLightPosition(
                                new Point3F(voxelSpace.getGravityCenter().x, voxelSpace.getGravityCenter().y,
                                        voxelSpace.getGravityCenter().z + voxelSpace.widthZ + 100));

                        /**
                         * *camera**
                         */
                        TrackballCamera trackballCamera = new TrackballCamera();
                        trackballCamera.setPivot(voxelSpace);
                        trackballCamera
                                .setLocation(new Vec3F(voxelSpace.getGravityCenter().x + voxelSpace.widthX,
                                        voxelSpace.getGravityCenter().y + voxelSpace.widthY,
                                        voxelSpace.getGravityCenter().z + voxelSpace.widthZ));
                        viewer3D.getScene().setCamera(trackballCamera);

                        Platform.runLater(new Runnable() {

                            @Override
                            public void run() {

                                final Stage toolBarFrameStage = new Stage();
                                final FXMLLoader loader = new FXMLLoader(
                                        getClass().getResource("/fxml/ToolBoxFrame.fxml"));

                                try {
                                    stage.setAlwaysOnTop(false);

                                    Parent root = loader.load();
                                    toolBarFrameStage.setScene(new Scene(root));
                                    toolBarFrameStage.initStyle(StageStyle.UNDECORATED);

                                    toolBarFrameStage.setAlwaysOnTop(true);

                                    ToolBoxFrameController toolBarFrameController = loader.getController();
                                    toolBarFrameController.setStage(toolBarFrameStage);
                                    toolBarFrameStage.setX(viewer3D.getPosition().getX());
                                    toolBarFrameStage.setY(viewer3D.getPosition().getY());
                                    toolBarFrameController.setJoglListener(viewer3D.getJoglContext());
                                    toolBarFrameController.setAttributes(attributeToView,
                                            voxelSpace.data.getVoxelSpaceInfos().getColumnNames());

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

                                                @Override
                                                public void changed(
                                                        ObservableValue<? extends Boolean> observable,
                                                        Boolean oldValue, Boolean newValue) {
                                                    if (newValue) {
                                                        toolBarFrameStage.setAlwaysOnTop(true);
                                                        toolBarFrameStage.setX(viewer3D.getPosition().getX());
                                                        toolBarFrameStage.setY(viewer3D.getPosition().getY());
                                                    } else if (!viewer3D.isFocused()) {
                                                        toolBarFrameStage.setAlwaysOnTop(false);
                                                    }
                                                }
                                            });

                                    toolBarFrameController.initContent(voxelSpace);
                                    toolBarFrameStage.setAlwaysOnTop(true);

                                    toolBarFrameStage.show();

                                    double maxToolBoxHeight = toolBarFrameStage.getHeight();
                                    viewer3D.getJoglContext().setStartX((int) toolBarFrameStage.getWidth());

                                    viewer3D.getRenderFrame().addWindowListener(new WindowAdapter() {

                                        @Override
                                        public void windowResized(com.jogamp.newt.event.WindowEvent we) {

                                            Window window = (Window) we.getSource();
                                            final double height = window.getHeight();

                                            Platform.runLater(new Runnable() {

                                                @Override
                                                public void run() {

                                                    if (height < maxToolBoxHeight) {
                                                        toolBarFrameStage.setHeight(height);
                                                    } else {
                                                        toolBarFrameStage.setHeight(maxToolBoxHeight);
                                                    }

                                                    toolBarFrameStage.setX(viewer3D.getPosition().getX());
                                                    toolBarFrameStage.setY(viewer3D.getPosition().getY());
                                                }
                                            });
                                        }

                                        @Override
                                        public void windowMoved(com.jogamp.newt.event.WindowEvent we) {

                                            Platform.runLater(new Runnable() {

                                                @Override
                                                public void run() {
                                                    toolBarFrameStage.setX(viewer3D.getPosition().getX());
                                                    toolBarFrameStage.setY(viewer3D.getPosition().getY());
                                                }
                                            });
                                        }

                                        @Override
                                        public void windowDestroyed(com.jogamp.newt.event.WindowEvent we) {

                                            Platform.runLater(new Runnable() {

                                                @Override
                                                public void run() {
                                                    toolBarFrameStage.close();

                                                    if (fcSaveVoxelFileForAreaExtracting == null) {
                                                        fcSaveVoxelFileForAreaExtracting = new FileChooserContext();

                                                        if (fcOpenVoxelFileForAreaExtracting != null) {
                                                            fcSaveVoxelFileForAreaExtracting.fc
                                                                    .setInitialDirectory(
                                                                            fcOpenVoxelFileForAreaExtracting.lastSelectedFile
                                                                                    .getParentFile());
                                                        }
                                                    }

                                                    File selectedFile = fcSaveVoxelFileForAreaExtracting
                                                            .showSaveDialog(stage);

                                                    if (selectedFile != null) {
                                                        VoxelFileReader reader;
                                                        BufferedWriter writer = null;

                                                        try {
                                                            reader = new VoxelFileReader(voxelFile, true);
                                                            VoxelSpaceInfos infos = reader.getVoxelSpaceInfos();

                                                            writer = new BufferedWriter(
                                                                    new FileWriter(selectedFile));

                                                            writer.write(infos.toString() + "\n");

                                                            Iterator<Voxel> iterator = reader.iterator();

                                                            while (iterator.hasNext()) {

                                                                Voxel voxel = iterator.next();

                                                                if (voxelsToRemove.contains(new Point3i(
                                                                        voxel.$i, voxel.$j, voxel.$k))) {
                                                                    voxel.PadBVTotal = 0;
                                                                    voxel.nbEchos = 0;
                                                                    voxel.transmittance = 1;
                                                                    voxel.bvIntercepted = 0;
                                                                }

                                                                writer.write(voxel + "\n");
                                                            }

                                                            writer.close();

                                                            addFileToProductsList(selectedFile);

                                                        } catch (Exception ex) {
                                                            showErrorDialog(ex);
                                                        } finally {
                                                            try {
                                                                if (writer != null) {
                                                                    writer.close();
                                                                }

                                                            } catch (IOException ex) {
                                                                showErrorDialog(ex);
                                                            }
                                                        }
                                                    }

                                                    editingFrameOpened = false;
                                                }
                                            });
                                        }

                                        @Override
                                        public void windowGainedFocus(com.jogamp.newt.event.WindowEvent we) {

                                            viewer3D.setIsFocused(true);

                                            Platform.runLater(new Runnable() {

                                                @Override
                                                public void run() {

                                                    if (!toolBarFrameStage.isShowing()) {
                                                        toolBarFrameStage.toFront();
                                                    }

                                                    toolBarFrameStage.setIconified(false);
                                                    toolBarFrameStage.setAlwaysOnTop(true);

                                                    toolBarFrameStage.setX(viewer3D.getPosition().getX());
                                                    toolBarFrameStage.setY(viewer3D.getPosition().getY());
                                                }
                                            });
                                        }

                                        @Override
                                        public void windowLostFocus(com.jogamp.newt.event.WindowEvent e) {

                                            viewer3D.setIsFocused(false);
                                            Platform.runLater(new Runnable() {

                                                @Override
                                                public void run() {
                                                    if (!toolBarFrameStage.focusedProperty().get()) {
                                                        toolBarFrameStage.setIconified(true);
                                                        toolBarFrameStage.setAlwaysOnTop(false);
                                                    }
                                                }
                                            });
                                        }
                                    });

                                    viewer3D.show();

                                    toolBarFrameStage.setAlwaysOnTop(true);

                                } catch (IOException e) {
                                    showErrorDialog(new Exception("Loading ToolBarFrame.fxml failed", e));
                                } catch (Exception e) {
                                    showErrorDialog(new Exception("Error occured during toolbar init", e));
                                }
                            }
                        });

                        return null;
                    }
                };
            }
        };

        ProgressDialog d = new ProgressDialog(s);
        d.show();

        s.start();

    } catch (Exception ex) {
        showErrorDialog(new Exception("Cannot launch 3d view", ex));
    }
}

From source file:pe.edu.system.jcmr.controlador.LoguinController.java

@FXML
public void btnOnSingIn(ActionEvent event) throws IOException {

    if (StringUtils.isBlank(txtUsuario.getText())) {
        lblMensaje.setText(/*from w  ww .j av  a2  s  .com*/
                getResourceMessage("required.campo.message", new Object[] { txtUsuario.getPromptText() }));
        return;
    }
    if (StringUtils.isBlank(txtPassword.getText())) {
        lblMensaje.setText(
                getResourceMessage("required.campo.message", new Object[] { txtPassword.getPromptText() }));
        return;
    }
    if (cboIdioma.getValue().getCodigo().equals("0")) {
        lblMensaje.setText(
                getResourceMessage("required.campo.message", new Object[] { cboIdioma.getPromptText() }));
        return;
    }
    Service<TbEmpleado> service = new Service<TbEmpleado>() {
        @Override
        protected Task<TbEmpleado> createTask() {
            return new Task<TbEmpleado>() {
                @Override
                protected TbEmpleado call() throws Exception {

                    TbEmpleado employed = employedService.authenticateUser(txtUsuario.getText(),
                            txtPassword.getText());

                    return employed;
                }
            };
        }

        @Override
        protected void succeeded() {
            SessionJCMR.getInstance().addContextObject("Usuario", getValue());
            SessionJCMR.getInstance().addContextObject("Lenguage", cboIdioma.getValue().getCodigo());
            closeWindow(btnSingIn);
            openWindow(MAIN_FXML);
        }

        @Override
        protected void failed() {
            lblMensaje.setText(getResourceMessage("errors.password.mismatch"));
        }

    };
    viewLoader.visibleProperty().bind(service.runningProperty());
    rgBack.visibleProperty().bind(service.runningProperty());
    service.start();

}