Example usage for javafx.stage Stage getIcons

List of usage examples for javafx.stage Stage getIcons

Introduction

In this page you can find the example usage for javafx.stage Stage getIcons.

Prototype

public final ObservableList<Image> getIcons() 

Source Link

Document

Gets the icon images to be used in the window decorations and when minimized.

Usage

From source file:snpviewer.SnpViewer.java

private void zoomRegion(Rectangle rectangle) {
    try {/*from   w w w .  j av  a 2  s .co m*/
        FXMLLoader loader = new FXMLLoader(getClass().getResource("ZoomRegionView.fxml"));
        ChromosomeLength chromLength = new ChromosomeLength(genomeVersion);
        String currentChrom = (String) chromosomeBoxList[chromosomeSelector.getSelectionModel()
                .getSelectedIndex()];
        double startCoordinate = chromLength.getLength(currentChrom) / selectionOverlayPane.getWidth()
                * rectangle.getX();
        double selectionWidth = chromLength.getLength(currentChrom) / selectionOverlayPane.getWidth()
                * rectangle.getWidth();
        if (rectangle.getX() == 0) {
            startCoordinate = 1;
        }

        Pane page = (Pane) loader.load();
        Scene scene = new Scene(page);
        Stage stage = new Stage();
        stage.setScene(scene);
        stage.setTitle("chr" + currentChrom + ":" + nf.format(startCoordinate) + "-"
                + nf.format(startCoordinate + selectionWidth));
        scene.getStylesheets().add(SnpViewer.class.getResource("SnpViewerStyleSheet.css").toExternalForm());
        String subPath = "zoom";
        stage.initModality(Modality.NONE);
        stage.getIcons().add(new Image(this.getClass().getResourceAsStream("icon.png")));
        stage.show();
        ZoomRegionViewController zoomController = (ZoomRegionViewController) loader.getController();
        ArrayList<SnpFile> bothFiles = new ArrayList<>();
        bothFiles.addAll(affFiles);
        bothFiles.addAll(unFiles);
        ArrayList<Pane> zoomPanes = zoomController.setPanes(bothFiles);
        zoomController.setParentController(this);
        zoomController.setLoadingRectangle(rectangle);
        zoomController.setRegionLength(selectionWidth);
        zoomController.setRegionStart(startCoordinate);
        zoomController.setChromosome(currentChrom);
        SplitPane zoomSplit = zoomController.getSplitPane();
        Iterator<SnpFile> sIter = bothFiles.iterator();
        Iterator<Pane> pIter = zoomPanes.iterator();
        if (!sIter.hasNext() || !pIter.hasNext()) {
            return;
        }
        SnpFile firstFile = sIter.next();
        Pane firstPane = pIter.next();
        drawCoordinatesWithIterator(firstFile, firstPane, subPath, sIter, pIter, 1, bothFiles.size(),
                currentChrom, startCoordinate, startCoordinate + selectionWidth, true, zoomSplit);
        zoomController.tidyPanes();

    } catch (ChromosomeLength.ChromosomeLengthException | IOException ex) {
        Dialogs.showErrorDialog(null, "Please see details for stack trace.", "Error displaying zoomed region",
                "SnpViewer", ex);
    }
}

From source file:snpviewer.SnpViewer.java

@Override
public void start(final Stage primaryStage) {
    try {//from  ww w .  j  av  a 2s .  c o m
        //FXMLLoader loader = new FXMLLoader(SnpViewer.class.getResource("SnpView.fxml"));
        AnchorPane page = (AnchorPane) FXMLLoader.load(SnpViewer.class.getResource("SnpView.fxml"));

        Scene scene = new Scene(page);
        primaryStage.setScene(scene);
        primaryStage.setTitle("SNP Viewer");
        scene.getStylesheets().add(SnpViewer.class.getResource("SnpViewerStyleSheet.css").toExternalForm());
        primaryStage.show();
        primaryStage.getIcons().add(new Image(this.getClass().getResourceAsStream("icon.png")));

        /*primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
        @Override
        public void handle(WindowEvent event) {
            try{
                DialogResponse response = Dialogs.showConfirmDialog(primaryStage,
                           "Any unsaved changes will be lost",
                           "Really quit?", "SNP View", DialogOptions.OK_CANCEL);
                if (DialogResponse.OK.equals(response)){
                    stop();
                }else {
                    event.consume();
                }
            }catch (Exception ex) {
                Logger.getLogger(SnpViewer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        });*/
    } catch (Exception ex) {
        Logger.getLogger(SnpViewer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:snpviewer.SnpViewer.java

public void autoFindRegions() {
    if (affObserve.isEmpty()) {
        Dialogs.showErrorDialog(null,/*www  . j a v a2 s  .  co m*/
                "Find Regions can only be run when there "
                        + "is at least one Affected sample in the project.  Use the "
                        + "'Add Affected' button/menu item to add  Affected samples.",
                "No Affected samples to analyze!", "SnpViewer");
        return;
    }
    Stage stage = new Stage();
    FXMLLoader loader = new FXMLLoader(getClass().getResource("FindRegionsInterface.fxml"));
    try {
        Pane page = (Pane) loader.load();
        FindRegionsInterfaceController findReg = (FindRegionsInterfaceController) loader.getController();
        Scene scene = new Scene(page);
        stage.setScene(scene);
        scene.getStylesheets().add(SnpViewer.class.getResource("SnpViewerStyleSheet.css").toExternalForm());
        setProgressMode(true);
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.getIcons().add(new Image(this.getClass().getResourceAsStream("icon.png")));
        stage.showAndWait();
        if (findReg.getCancelled()) {
            setProgressMode(false);
            return;
        }

        //int w, double r, boolean con, int refWind, double refCut,
        //int minReportSize, int minReportRun, double het, double dischord)
        int window = Integer.parseInt(findReg.getWindow());
        double regionLength = Double.parseDouble(findReg.getRegionLength());
        boolean checkConcordant = findReg.getCheckConcordance();
        int refineWindow = Integer.parseInt(findReg.getRefineSize());
        double refineTolerance = Double.parseDouble(findReg.getRefineTolerance());
        int minReport = Integer.parseInt(findReg.getReportLength());
        int minReportRun = Integer.parseInt(findReg.getReportMinSnps());
        double hetTolerance = Double.parseDouble(findReg.getHetTolerance());
        double dischordTolerance = Double.parseDouble(findReg.getDischordTolerance());
        boolean autosomesOnly = findReg.getAutosomesOnly();
        LinkedHashSet<String> c = new LinkedHashSet();
        for (Object item : chromosomeSelector.getItems()) {
            if (item instanceof String) {
                String chrom = (String) item;
                if (autosomesOnly) {
                    if (chrom.matches("\\d+")) {//only add autosomes
                        c.add(chrom);
                    }
                } else {
                    c.add(chrom);
                }
            }
        }

        final RegionFinder regionFinder = new RegionFinder(c, affFiles, unFiles, window, regionLength,
                checkConcordant, refineWindow, refineTolerance, minReport, minReportRun, hetTolerance,
                dischordTolerance);

        regionFinder.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                progressBar.progressProperty().unbind();
                progressMessage.textProperty().unbind();
                progressMessage.setText("Done");
                progressTitle.textProperty().unbind();
                setProgressMode(false);
                Object result = t.getSource().getValue();
                ArrayList<RegionSummary> foundRegions = new ArrayList<>();
                if (result instanceof ArrayList) {
                    for (Object r : (ArrayList) result) {
                        if (r instanceof RegionSummary) {
                            RegionSummary reg = (RegionSummary) r;
                            foundRegions.add(reg);
                        }
                    }
                    if (foundRegions.size() > 0) {
                        FXMLLoader tableLoader = new FXMLLoader(
                                getClass().getResource("MultiRegionReporter.fxml"));
                        try {
                            Pane tablePane = (Pane) tableLoader.load();
                            MultiRegionReporterController multiReg = (MultiRegionReporterController) tableLoader
                                    .getController();
                            Scene tableScene = new Scene(tablePane);
                            Stage tableStage = new Stage();
                            tableStage.setScene(tableScene);
                            tableScene.getStylesheets().add(
                                    SnpViewer.class.getResource("SnpViewerStyleSheet.css").toExternalForm());
                            multiReg.displayData(foundRegions);
                            tableStage.setTitle("Find Regions Results");
                            tableStage.getIcons()
                                    .add(new Image(this.getClass().getResourceAsStream("icon.png")));
                            tableStage.initModality(Modality.NONE);
                            tableStage.show();
                        } catch (Exception ex) {
                            Dialogs.showErrorDialog(null,
                                    "Error displaying" + " results from Find Regions Method.",
                                    "Find Regions Error!", "SnpViewer", ex);
                        }
                    } else {
                        Dialogs.showInformationDialog(null, "No regions " + "found.", "Find Regions",
                                "SnpViewer");
                    }
                    savedRegions.addAll(foundRegions);
                    RegionSummary sorter = new RegionSummary();
                    sorter.mergeRegionsByPosition(savedRegions);
                }
                saveProject();
                int c = chromosomeSelector.getSelectionModel().getSelectedIndex();
                if (c > -1) {
                    selectionOverlayPane.getChildren().clear();
                    selectionOverlayPane.getChildren().add(dragSelectRectangle);
                    drawSavedRegions((String) chromosomeBoxList[c]);
                }
                progressMessage.setText("");
                progressTitle.setText("");
                progressBar.progressProperty().set(0);
            }
        });
        regionFinder.setOnFailed(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                progressBar.progressProperty().unbind();
                progressMessage.textProperty().unbind();
                progressMessage.setText("Failed!");
                progressTitle.textProperty().unbind();
                Dialogs.showErrorDialog(null, "Find Regions method failed.", "Error!", "SnpViewer",
                        t.getSource().getException());
                setProgressMode(false);
                progressMessage.setText("");
                progressTitle.setText("");
                progressBar.progressProperty().set(0);
            }
        });
        regionFinder.setOnCancelled(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                progressBar.progressProperty().unbind();
                progressMessage.textProperty().unbind();
                progressMessage.setText("Cancelled");
                progressTitle.textProperty().unbind();
                Dialogs.showErrorDialog(null, "Find Regions method Cancelled.", "Cancelled", "SnpViewer");
                setProgressMode(false);
                progressMessage.setText("");
                progressTitle.setText("");
                progressBar.progressProperty().set(0);

            }
        });
        cancelButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                regionFinder.cancel();

            }
        });
        progressBar.progressProperty().unbind();
        progressMessage.textProperty().unbind();
        progressTitle.textProperty().unbind();
        progressBar.progressProperty().bind(regionFinder.progressProperty());
        progressMessage.textProperty().bind(regionFinder.messageProperty());
        progressTitle.textProperty().bind(regionFinder.titleProperty());
        regionFinder.start();

    } catch (IOException ex) {
        Dialogs.showErrorDialog(null, "Error starting Find Regions method.", "Error!", "SnpViewer", ex);
        progressBar.progressProperty().unbind();
        progressMessage.textProperty().unbind();
        progressTitle.textProperty().unbind();
        setProgressMode(false);
    }

}

From source file:org.jevis.jeconfig.JEConfig.java

/**
 * Build an new JEConfig Login and main frame/stage
 *
 * @param primaryStage/*from  w w w  . ja  va 2s. c o  m*/
 */
//AITBilal - Login  
private void initGUI(Stage primaryStage) {
    Scene scene;
    LoginGlass login = new LoginGlass(primaryStage);

    AnchorPane jeconfigRoot = new AnchorPane();
    AnchorPane.setTopAnchor(jeconfigRoot, 0.0);
    AnchorPane.setRightAnchor(jeconfigRoot, 0.0);
    AnchorPane.setLeftAnchor(jeconfigRoot, 0.0);
    AnchorPane.setBottomAnchor(jeconfigRoot, 0.0);
    //        jeconfigRoot.setStyle("-fx-background-color: white;");
    //        jeconfigRoot.getChildren().setAll(new Label("sodfhsdhdsofhdshdsfdshfjf"));

    Screen screen = Screen.getPrimary();
    Rectangle2D bounds = screen.getVisualBounds();

    // @AITBilal - Main frame elemente wird aufgerufen nachdem man sich eingeloggt hat.
    login.getLoginStatus().addListener(new ChangeListener<Boolean>() {

        @Override
        public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
            if (newValue) {
                System.out.println("after request");
                _mainDS = login.getDataSource();
                ds = _mainDS;

                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        FadeTransition ft = new FadeTransition(Duration.millis(1500), login);
                        ft.setFromValue(1.0);
                        ft.setToValue(0);
                        ft.setCycleCount(1);
                        ft.play();
                    }
                });

                JEConfig.PROGRAMM_INFO.setJEVisAPI(ds.getInfo());
                JEConfig.PROGRAMM_INFO.addLibrary(org.jevis.commons.application.Info.INFO);
                JEConfig.PROGRAMM_INFO.addLibrary(org.jevis.application.Info.INFO);

                preLodedClasses = login.getAllClasses();
                preLodedRootObjects = login.getRootObjects();

                PluginManager pMan = new PluginManager(ds);
                //@AITBilal - Toolbar fr save, newB, delete, sep1, form
                GlobalToolBar toolbar = new GlobalToolBar(pMan);
                pMan.addPluginsByUserSetting(null);

                //                    StackPane root = new StackPane();
                //                    root.setId("mainpane");
                BorderPane border = new BorderPane();
                VBox vbox = new VBox();
                vbox.getChildren().addAll(new TopMenu(), toolbar.ToolBarFactory());
                border.setTop(vbox);
                //@AITBilal - Alle Plugins Inhalt fr JEConfig (Resources... | System | Attribute)
                border.setCenter(pMan.getView());

                Statusbar statusBar = new Statusbar(ds);

                border.setBottom(statusBar);

                System.out.println("show welcome");

                //Disable GUI is StatusBar note an disconnect
                border.disableProperty().bind(statusBar.connectedProperty.not());

                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        AnchorPane.setTopAnchor(border, 0.0);
                        AnchorPane.setRightAnchor(border, 0.0);
                        AnchorPane.setLeftAnchor(border, 0.0);
                        AnchorPane.setBottomAnchor(border, 0.0);

                        jeconfigRoot.getChildren().setAll(border);
                        //                            try {
                        //            WelcomePage welcome = new WelcomePage(primaryStage, new URI("http://coffee-project.eu/"));
                        //            WelcomePage welcome = new WelcomePage(primaryStage, new URI("http://openjevis.org/projects/openjevis/wiki/JEConfig3#JEConfig-Version-3"));

                        //                            Task<Void> showWelcome = new Task<Void>() {
                        //                                @Override
                        //                                protected Void call() throws Exception {
                        try {
                            WelcomePage welcome = new WelcomePage(primaryStage, _config.getWelcomeURL());
                        } catch (URISyntaxException ex) {
                            Logger.getLogger(JEConfig.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (MalformedURLException ex) {
                            Logger.getLogger(JEConfig.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        //                                    return null;
                        //                                }
                        //                            };
                        //                            new Thread(showWelcome).start();

                        //                                WelcomePage welcome = new WelcomePage(primaryStage, _config.getWelcomeURL());
                        //                            } catch (URISyntaxException ex) {
                        //                                Logger.getLogger(JEConfig.class.getName()).log(Level.SEVERE, null, ex);
                        //                            } catch (MalformedURLException ex) {
                        //                                Logger.getLogger(JEConfig.class.getName()).log(Level.SEVERE, null, ex);
                        //                            }
                    }
                });
            }

        }
    });

    AnchorPane.setTopAnchor(login, 0.0);
    AnchorPane.setRightAnchor(login, 0.0);
    AnchorPane.setLeftAnchor(login, 0.0);
    AnchorPane.setBottomAnchor(login, 0.0);
    //@AITBilal - Login Dialog
    scene = new Scene(jeconfigRoot, bounds.getWidth(), bounds.getHeight());
    scene.getStylesheets().add("/styles/Styles.css");
    primaryStage.getIcons().add(getImage("1393354629_Config-Tools.png"));
    primaryStage.setTitle("JEConfig");
    primaryStage.setScene(scene);
    maximize(primaryStage);
    primaryStage.show();

    //        Platform.runLater(new Runnable() {
    //            @Override
    //            public void run() {
    //@AITBilal - Inhalt bzw. die Elemente von LoginDialog
    jeconfigRoot.getChildren().setAll(login);
    //            }
    //        });

    primaryStage.onCloseRequestProperty().addListener(new ChangeListener<EventHandler<WindowEvent>>() {

        @Override
        public void changed(ObservableValue<? extends EventHandler<WindowEvent>> ov,
                EventHandler<WindowEvent> t, EventHandler<WindowEvent> t1) {
            try {
                System.out.println("Disconnect");
                ds.disconnect();
            } catch (JEVisException ex) {
                Logger.getLogger(JEConfig.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
}

From source file:uk.co.everywheremusic.viewcontroller.SetupScene.java

private void startSetupWindow(Stage primaryStage) {
    try {//from w  ww  .  j a  v a 2 s .  c  om
        installFolder = new File(".").getCanonicalPath() + Globals.INSTALL_EXT;
    } catch (IOException ex) {
        Logger.getLogger(SetupScene.class.getName()).log(Level.SEVERE, null, ex);
        installFolder = System.getProperty("user.dir") + Globals.INSTALL_EXT;
    }

    primaryStage.setTitle(Globals.APP_NAME);

    grid = new GridPane();
    grid.setAlignment(Pos.CENTER);
    grid.setHgap(10);
    grid.setVgap(10);
    grid.setPadding(new Insets(25, 25, 25, 25));

    column1 = new ColumnConstraints(100, 100, Double.MAX_VALUE);
    column1.setHgrow(Priority.ALWAYS);
    column2 = new ColumnConstraints(100, 100, Double.MAX_VALUE);
    column2.setHgrow(Priority.ALWAYS);
    column3 = new ColumnConstraints(100, 100, Double.MAX_VALUE);
    column3.setHgrow(Priority.ALWAYS);
    column4 = new ColumnConstraints(100, 100, Double.MAX_VALUE);
    column4.setHgrow(Priority.ALWAYS);
    grid.getColumnConstraints().addAll(column1, column2, column3, column4);

    sceneTitle = new Label(Globals.SETUP_FRAME_TITLE);
    sceneTitle.setId(Globals.CSS_TITLE_ID);
    sceneTitle.setPrefWidth(Double.MAX_VALUE);
    sceneTitle.setAlignment(Pos.CENTER);

    ImageView imageView = null;
    try {

        imageView = new ImageView();
        String img = new File(Globals.IC_LOGO).toURI().toURL().toString();
        imgLogo = new Image(img);

        imageView.setImage(imgLogo);

    } catch (MalformedURLException ex) {
        Logger.getLogger(ServerScene.class.getName()).log(Level.SEVERE, null, ex);
    }

    GridPane titlePane = new GridPane();
    ColumnConstraints c1 = new ColumnConstraints(50);
    ColumnConstraints c2 = new ColumnConstraints(400);
    titlePane.getColumnConstraints().addAll(c1, c2);
    titlePane.add(imageView, 0, 0);
    titlePane.add(sceneTitle, 1, 0);
    titlePane.setAlignment(Pos.CENTER);
    grid.add(titlePane, 0, 0, 4, 1);

    lblFolder = new Label(Globals.SETUP_LBL_MUSIC_FOLDER);
    grid.add(lblFolder, 0, 2, 3, 1);

    txtFolder = new TextField();
    txtFolder.setText("/home/kyle/Music/Test music");
    grid.add(txtFolder, 0, 3, 3, 1);

    btnFolder = new Button(Globals.SETUP_BTN_MUSIC_FOLDER);
    btnFolder.setPrefWidth(Double.MAX_VALUE);
    grid.add(btnFolder, 3, 3);

    final DirectoryChooser dirChooser = new DirectoryChooser();

    btnFolder.setOnAction((ActionEvent event) -> {
        File dir = dirChooser.showDialog(primaryStage);
        if (dir != null) {
            txtFolder.setText(dir.getAbsolutePath());
        }
    });

    lblPassword = new Label("Choose a password:");
    grid.add(lblPassword, 0, 4, 2, 1);

    lblConfirmPassword = new Label("Confirm your password:");
    grid.add(lblConfirmPassword, 2, 4, 2, 1);

    txtPassword = new PasswordField();
    grid.add(txtPassword, 0, 5, 2, 1);

    txtConfirmPassword = new PasswordField();
    grid.add(txtConfirmPassword, 2, 5, 1, 1);

    textArea = new TextArea();
    textArea.setPrefHeight(Double.MAX_VALUE);
    textArea.setDisable(true);
    textArea.setWrapText(true);
    grid.add(textArea, 0, 7, 4, 2);

    StackPane progressPane = new StackPane();
    lblProgress = new Label(Globals.SETUP_LBL_PERCENT);
    lblProgress.setId(Globals.CSS_PROGBAR_LBL_ID);
    lblProgress.setVisible(false);
    progressBar = new ProgressBar(0);
    progressBar.setPrefWidth(Double.MAX_VALUE);
    progressBar.setVisible(false);
    progressPane.getChildren().addAll(progressBar, lblProgress);
    progressPane.setAlignment(Pos.CENTER_RIGHT);
    grid.add(progressPane, 0, 11, 3, 1);

    StackPane buttonPane = new StackPane();
    btnInstall = new Button(Globals.SETUP_BTN_INSTALL);
    btnInstall.setPrefWidth(Double.MAX_VALUE);
    btnDone = new Button(Globals.SETUP_BTN_DONE);
    btnDone.setPrefWidth(Double.MAX_VALUE);
    btnDone.setVisible(false);
    buttonPane.getChildren().addAll(btnInstall, btnDone);
    grid.add(buttonPane, 3, 11);

    btnInstall.setOnAction((ActionEvent event) -> {

        boolean valid = validateForm();
        if (valid) {

            lblFolder.setDisable(true);
            txtFolder.setDisable(true);
            btnFolder.setDisable(true);
            lblPassword.setDisable(true);
            txtPassword.setDisable(true);
            lblConfirmPassword.setDisable(true);
            txtConfirmPassword.setDisable(true);

            textArea.setDisable(false);
            lblProgress.setVisible(true);
            progressBar.setVisible(true);
            btnInstall.setDisable(true);

            musicFolder = txtFolder.getText();
            password = txtPassword.getText();

            setupWorker = createSetupWorker();
            progressBar.progressProperty().unbind();
            progressBar.progressProperty().bind(setupWorker.progressProperty());

            setupWorker.messageProperty().addListener(
                    (ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
                        String[] values = newValue.split("\\|");
                        lblProgress.setText(values[0] + "%");
                        textArea.appendText(values[1] + "\n");

                        if (values[1].equals(Globals.SETUP_MSG_DONE)) {
                            btnInstall.setVisible(false);
                            btnDone.setVisible(true);
                        }

                    });

            new Thread(setupWorker).start();

        }
    });

    btnDone.setOnAction((ActionEvent event) -> {
        primaryStage.hide();
        new ServerScene(installFolder, musicFolder).showWindow(new Stage());
    });

    try {
        String imgUrl = new File(Globals.IC_LOGO).toURI().toURL().toString();
        javafx.scene.image.Image i = new javafx.scene.image.Image(imgUrl);
        primaryStage.getIcons().add(i);
    } catch (MalformedURLException ex) {
        Logger.getLogger(ServerScene.class.getName()).log(Level.SEVERE, null, ex);
    }

    scene = new Scene(grid, 600, 400);
    primaryStage.setScene(scene);

    scene.getStylesheets().add(SetupScene.class.getResource(Globals.CSS_FILE).toExternalForm());
    //  grid.setGridLinesVisible(true);
    primaryStage.show();
}

From source file:nl.rivm.cib.episim.model.disease.infection.MSEIRSPlot.java

@Override
public void start(final Stage stage) {
    final SIRConfig conf = ConfigFactory.create(SIRConfig.class);
    final double[] t = conf.t();
    final long[] pop = conf.population();
    final double n0 = Arrays.stream(pop).sum();
    final String[] colors = conf.colors(), colors2 = conf.colors2();

    final Pane plot = new Pane();
    plot.setPrefSize(400, 300);/*from  ww  w .  ja  v  a  2s  .c o  m*/
    plot.setMinSize(50, 50);

    final NumberAxis xAxis = new NumberAxis(t[0], t[1], (t[1] - t[0]) / 10);
    final NumberAxis yAxis = new NumberAxis(0, n0, n0 / 10);
    final Pane axes = new Pane();
    axes.prefHeightProperty().bind(plot.heightProperty());
    axes.prefWidthProperty().bind(plot.widthProperty());

    xAxis.setSide(Side.BOTTOM);
    xAxis.setMinorTickVisible(false);
    xAxis.setPrefWidth(axes.getPrefWidth());
    xAxis.prefWidthProperty().bind(axes.widthProperty());
    xAxis.layoutYProperty().bind(axes.heightProperty());

    yAxis.setSide(Side.LEFT);
    yAxis.setMinorTickVisible(false);
    yAxis.setPrefHeight(axes.getPrefHeight());
    yAxis.prefHeightProperty().bind(axes.heightProperty());
    yAxis.layoutXProperty().bind(Bindings.subtract(1, yAxis.widthProperty()));
    axes.getChildren().setAll(xAxis, yAxis);

    final Label lbl = new Label(String.format("R0=%.1f, recovery=%.1ft\nSIR(0)=%s", conf.reproduction(),
            conf.recovery(), Arrays.toString(pop)));
    lbl.setTextAlignment(TextAlignment.CENTER);
    lbl.setTextFill(Color.WHITE);

    final Path[] deterministic = { new Path(), new Path(), new Path() };
    IntStream.range(0, pop.length).forEach(i -> {
        final Color color = Color.valueOf(colors[i]);
        final Path path = deterministic[i];
        path.setStroke(color.deriveColor(0, 1, 1, 0.6));
        path.setStrokeWidth(2);
        path.setClip(new Rectangle(0, 0, plot.getPrefWidth(), plot.getPrefHeight()));
    });

    plot.getChildren().setAll(axes);

    // fill paths with integration estimates
    final double xl = xAxis.getLowerBound(), sx = plot.getPrefWidth() / (xAxis.getUpperBound() - xl),
            yh = plot.getPrefHeight(), sy = yh / (yAxis.getUpperBound() - yAxis.getLowerBound());
    final TreeMap<Double, Integer> iDeterministic = new TreeMap<>();

    MSEIRSTest.deterministic(conf, () -> new DormandPrince853Integrator(1.0E-8, 10, 1.0E-20, 1.0E-20))
            .subscribe(yt -> {
                iDeterministic.put(yt.getKey(), deterministic[0].getElements().size());
                final double[] y = yt.getValue();
                final double x = (yt.getKey() - xl) * sx;
                for (int i = 0; i < y.length; i++) {
                    final double yi = yh - y[i] * sy;
                    final PathElement di = deterministic[i].getElements().isEmpty() ? new MoveTo(x, yi)
                            : new LineTo(x, yi);
                    deterministic[i].getElements().add(di);
                }
            }, e -> LOG.error("Problem", e), () -> plot.getChildren().addAll(deterministic));

    final Path[] stochasticTau = { new Path(), new Path(), new Path() };
    IntStream.range(0, pop.length).forEach(i -> {
        final Color color = Color.valueOf(colors[i]);
        final Path path = stochasticTau[i];
        path.setStroke(color);
        path.setStrokeWidth(1);
        path.setClip(new Rectangle(0, 0, plot.getPrefWidth(), plot.getPrefHeight()));
    });

    final TreeMap<Double, Integer> iStochasticTau = new TreeMap<>();
    MSEIRSTest.stochasticGillespie(conf).subscribe(yt -> {
        final double x = (yt.getKey() - xl) * sx;
        iStochasticTau.put(yt.getKey(), stochasticTau[0].getElements().size());
        final long[] y = yt.getValue();
        for (int i = 0; i < y.length; i++) {
            final double yi = yh - y[i] * sy;
            final ObservableList<PathElement> path = stochasticTau[i].getElements();
            if (path.isEmpty()) {
                path.add(new MoveTo(x, yi)); // first
            } else {
                final PathElement last = path.get(path.size() - 1);
                final double y_prev = last instanceof MoveTo ? ((MoveTo) last).getY() : ((LineTo) last).getY();
                path.add(new LineTo(x, y_prev));
                path.add(new LineTo(x, yi));
            }
        }
    }, e -> LOG.error("Problem", e), () -> plot.getChildren().addAll(stochasticTau));

    final Path[] stochasticRes = { new Path(), new Path(), new Path() };
    IntStream.range(0, pop.length).forEach(i -> {
        final Color color = Color.valueOf(colors2[i]);
        final Path path = stochasticRes[i];
        path.setStroke(color);
        path.setStrokeWidth(1);
        path.setClip(new Rectangle(0, 0, plot.getPrefWidth(), plot.getPrefHeight()));
    });

    final TreeMap<Double, Integer> iStochasticRes = new TreeMap<>();
    MSEIRSTest.stochasticSellke(conf).subscribe(yt -> {
        final double x = (yt.getKey() - xl) * sx;
        iStochasticRes.put(yt.getKey(), stochasticRes[0].getElements().size());
        final long[] y = yt.getValue();
        for (int i = 0; i < y.length; i++) {
            final double yi = yh - y[i] * sy;
            final ObservableList<PathElement> path = stochasticRes[i].getElements();
            if (path.isEmpty()) {
                path.add(new MoveTo(x, yi)); // first
            } else {
                final PathElement last = path.get(path.size() - 1);
                final double y_prev = last instanceof MoveTo ? ((MoveTo) last).getY() : ((LineTo) last).getY();
                path.add(new LineTo(x, y_prev));
                path.add(new LineTo(x, yi));
            }
        }
    }, e -> LOG.error("Problem", e), () -> plot.getChildren().addAll(stochasticRes));

    // auto-scale on stage/plot resize 
    // FIXME scaling around wrong origin, use ScatterChart?
    //         xAxis.widthProperty()
    //               .addListener( (ChangeListener<Number>) ( observable,
    //                  oldValue, newValue ) ->
    //               {
    //                  final double scale = ((Double) newValue)
    //                        / plot.getPrefWidth();
    //                  plot.getChildren().filtered( n -> n instanceof Path )
    //                        .forEach( n ->
    //                        {
    //                           final Path path = (Path) n;
    //                           path.setScaleX( scale );
    //                           path.setTranslateX( (path
    //                                 .getBoundsInParent().getWidth()
    //                                 - path.getLayoutBounds().getWidth())
    //                                 / 2 );
    //                        } );
    //               } );
    //         plot.heightProperty()
    //               .addListener( (ChangeListener<Number>) ( observable,
    //                  oldValue, newValue ) ->
    //               {
    //                  final double scale = ((Double) newValue)
    //                        / plot.getPrefHeight();
    //                  plot.getChildren().filtered( n -> n instanceof Path )
    //                        .forEach( n ->
    //                        {
    //                           final Path path = (Path) n;
    //                           path.setScaleY( scale );
    //                           path.setTranslateY(
    //                                 (path.getBoundsInParent()
    //                                       .getHeight() * (scale - 1))
    //                                       / 2 );
    //                        } );
    //               } );

    final StackPane layout = new StackPane(lbl, plot);
    layout.setAlignment(Pos.TOP_CENTER);
    layout.setPadding(new Insets(50));
    layout.setStyle("-fx-background-color: rgb(35, 39, 50);");

    final Line vertiCross = new Line();
    vertiCross.setStroke(Color.SILVER);
    vertiCross.setStrokeWidth(1);
    vertiCross.setVisible(false);
    axes.getChildren().add(vertiCross);

    final Tooltip tip = new Tooltip("");
    tip.setAutoHide(false);
    tip.hide();
    axes.setOnMouseExited(ev -> tip.hide());
    axes.setOnMouseMoved(ev -> {
        final Double x = (Double) xAxis.getValueForDisplay(ev.getX());
        if (x > xAxis.getUpperBound() || x < xAxis.getLowerBound()) {
            tip.hide();
            vertiCross.setVisible(false);
            return;
        }
        final Double y = (Double) yAxis.getValueForDisplay(ev.getY());
        if (y > yAxis.getUpperBound() || y < yAxis.getLowerBound()) {
            tip.hide();
            vertiCross.setVisible(false);
            return;
        }
        final double xs = xAxis.getDisplayPosition(x);
        vertiCross.setStartX(xs);
        vertiCross.setStartY(yAxis.getDisplayPosition(0));
        vertiCross.setEndX(xs);
        vertiCross.setEndY(yAxis.getDisplayPosition(yAxis.getUpperBound()));
        vertiCross.setVisible(true);
        final int i = (iDeterministic.firstKey() > x ? iDeterministic.firstEntry()
                : iDeterministic.floorEntry(x)).getValue();
        final Object[] yi = Arrays.stream(deterministic).mapToDouble(p -> getY(p, i))
                .mapToObj(yAxis::getValueForDisplay).map(n -> DecimalUtil.toScale(n, 1)).toArray();
        final int j = (iStochasticTau.firstKey() > x ? iStochasticTau.firstEntry()
                : iStochasticTau.floorEntry(x)).getValue();
        final Object[] yj = Arrays.stream(stochasticTau).mapToDouble(p -> getY(p, j))
                .mapToObj(yAxis::getValueForDisplay).map(n -> DecimalUtil.toScale(n, 0)).toArray();
        final int k = (iStochasticRes.firstKey() > x ? iStochasticRes.firstEntry()
                : iStochasticRes.floorEntry(x)).getValue();
        final Object[] yk = Arrays.stream(stochasticRes).mapToDouble(p -> getY(p, k))
                .mapToObj(yAxis::getValueForDisplay).map(n -> DecimalUtil.toScale(n, 0)).toArray();
        final String txt = String.format("SIR(t=%.1f)\n" + "~det%s\n" + "~tau%s\n" + "~res%s", x,
                Arrays.toString(yi), Arrays.toString(yj), Arrays.toString(yk));

        tip.setText(txt);
        tip.show(axes, ev.getScreenX() - ev.getSceneX() + xs, ev.getScreenY() + 15);
    });

    try {
        stage.getIcons().add(new Image(FileUtil.toInputStream("icon.jpg")));
    } catch (final IOException e) {
        LOG.error("Problem", e);
    }
    stage.setTitle("Deterministic vs. Stochastic");
    stage.setScene(new Scene(layout, Color.rgb(35, 39, 50)));
    //         stage.setOnHidden( ev -> tip.hide() );
    stage.show();
}