List of usage examples for javafx.scene.control ContextMenu show
@Override public void show(Node anchor, double screenX, double screenY)
From source file:org.sleuthkit.autopsy.imageanalyzer.gui.GroupPane.java
/** * called automatically during constructor by FXMLConstructor. * * checks that FXML loading went ok and performs additional setup *//*from w w w . ja v a 2 s . c o m*/ @FXML void initialize() { assert gridView != null : "fx:id=\"tilePane\" was not injected: check your FXML file 'GroupPane.fxml'."; assert grpCatSplitMenu != null : "fx:id=\"grpCatSplitMenu\" was not injected: check your FXML file 'GroupHeader.fxml'."; assert grpTagSplitMenu != null : "fx:id=\"grpTagSplitMenu\" was not injected: check your FXML file 'GroupHeader.fxml'."; assert headerToolBar != null : "fx:id=\"headerToolBar\" was not injected: check your FXML file 'GroupHeader.fxml'."; assert segButton != null : "fx:id=\"previewList\" was not injected: check your FXML file 'GroupHeader.fxml'."; assert slideShowToggle != null : "fx:id=\"segButton\" was not injected: check your FXML file 'GroupHeader.fxml'."; assert tileToggle != null : "fx:id=\"tileToggle\" was not injected: check your FXML file 'GroupHeader.fxml'."; grouping.addListener(new InvalidationListener() { private void updateFiles() { final ObservableList<Long> fileIds = grouping.get().fileIds(); Platform.runLater(() -> { gridView.setItems(FXCollections.observableArrayList(fileIds)); }); resetHeaderString(); } @Override public void invalidated(Observable o) { getScrollBar().ifPresent((scrollBar) -> { scrollBar.setValue(0); }); //set the embeded header resetHeaderString(); //and assign fileIDs to gridView if (grouping.get() == null) { Platform.runLater(gridView.getItems()::clear); } else { grouping.get().fileIds().addListener((Observable observable) -> { updateFiles(); }); updateFiles(); } } }); //configure flashing glow animation on next unseen group button flashAnimation.setCycleCount(Timeline.INDEFINITE); flashAnimation.setAutoReverse(true); //configure gridView cell properties gridView.cellHeightProperty().bind(Toolbar.getDefault().sizeSliderValue().add(75)); gridView.cellWidthProperty().bind(Toolbar.getDefault().sizeSliderValue().add(75)); gridView.setCellFactory((GridView<Long> param) -> new DrawableCell()); //configure toolbar properties HBox.setHgrow(spacer, Priority.ALWAYS); spacer.setMinWidth(Region.USE_PREF_SIZE); ArrayList<MenuItem> grpTagMenues = new ArrayList<>(); for (final TagName tn : TagUtils.getNonCategoryTagNames()) { MenuItem menuItem = createGrpTagMenuItem(tn); grpTagMenues.add(menuItem); } try { grpTagSplitMenu.setText(TagUtils.getFollowUpTagName().getDisplayName()); grpTagSplitMenu.setOnAction(createGrpTagMenuItem(TagUtils.getFollowUpTagName()).getOnAction()); } catch (TskCoreException tskCoreException) { LOGGER.log(Level.WARNING, "failed to load FollowUpTagName", tskCoreException); } grpTagSplitMenu.setGraphic(new ImageView(DrawableAttribute.TAGS.getIcon())); grpTagSplitMenu.getItems().setAll(grpTagMenues); ArrayList<MenuItem> grpCategoryMenues = new ArrayList<>(); for (final Category cat : Category.values()) { MenuItem menuItem = createGrpCatMenuItem(cat); grpCategoryMenues.add(menuItem); } grpCatSplitMenu.setText(Category.FIVE.getDisplayName()); grpCatSplitMenu.setGraphic(new ImageView(DrawableAttribute.CATEGORY.getIcon())); grpCatSplitMenu.getItems().setAll(grpCategoryMenues); grpCatSplitMenu.setOnAction(createGrpCatMenuItem(Category.FIVE).getOnAction()); Runnable syncMode = () -> { switch (groupViewMode.get()) { case SLIDE_SHOW: slideShowToggle.setSelected(true); break; case TILE: tileToggle.setSelected(true); break; } }; syncMode.run(); //make togle states match view state groupViewMode.addListener((o) -> { syncMode.run(); }); slideShowToggle.toggleGroupProperty().addListener((o) -> { slideShowToggle.getToggleGroup().selectedToggleProperty() .addListener((observable, oldToggle, newToggle) -> { if (newToggle == null) { oldToggle.setSelected(true); } }); }); //listen to toggles and update view state slideShowToggle.setOnAction((ActionEvent t) -> { activateSlideShowViewer(globalSelectionModel.lastSelectedProperty().get()); }); tileToggle.setOnAction((ActionEvent t) -> { activateTileViewer(); }); controller.viewState().addListener((ObservableValue<? extends GroupViewState> observable, GroupViewState oldValue, GroupViewState newValue) -> { setViewState(newValue); }); addEventFilter(KeyEvent.KEY_PRESSED, tileKeyboardNavigationHandler); gridView.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { private ContextMenu buildContextMenu() { ArrayList<MenuItem> menuItems = new ArrayList<>(); menuItems.add(CategorizeAction.getPopupMenu()); menuItems.add(AddDrawableTagAction.getInstance().getPopupMenu()); Collection<? extends ContextMenuActionsProvider> menuProviders = Lookup.getDefault() .lookupAll(ContextMenuActionsProvider.class); for (ContextMenuActionsProvider provider : menuProviders) { for (final Action act : provider.getActions()) { if (act instanceof Presenter.Popup) { Presenter.Popup aact = (Presenter.Popup) act; menuItems.add(SwingMenuItemAdapter.create(aact.getPopupPresenter())); } } } final MenuItem extractMenuItem = new MenuItem("Extract File(s)"); extractMenuItem.setOnAction((ActionEvent t) -> { SwingUtilities.invokeLater(() -> { TopComponent etc = WindowManager.getDefault() .findTopComponent(ImageAnalyzerTopComponent.PREFERRED_ID); ExtractAction.getInstance().actionPerformed(new java.awt.event.ActionEvent(etc, 0, null)); }); }); menuItems.add(extractMenuItem); ContextMenu contextMenu = new ContextMenu(menuItems.toArray(new MenuItem[] {})); contextMenu.setAutoHide(true); return contextMenu; } @Override public void handle(MouseEvent t) { switch (t.getButton()) { case PRIMARY: if (t.getClickCount() == 1) { globalSelectionModel.clearSelection(); if (contextMenu != null) { contextMenu.hide(); } } t.consume(); break; case SECONDARY: if (t.getClickCount() == 1) { selectAllFiles(); } if (contextMenu == null) { contextMenu = buildContextMenu(); } contextMenu.hide(); contextMenu.show(GroupPane.this, t.getScreenX(), t.getScreenY()); t.consume(); break; } } }); // Platform.runLater(() -> { ActionUtils.configureButton(nextGroupAction, nextButton); final EventHandler<ActionEvent> onAction = nextButton.getOnAction(); nextButton.setOnAction((ActionEvent event) -> { flashAnimation.stop(); nextButton.setEffect(null); onAction.handle(event); }); ActionUtils.configureButton(forwardAction, forwardButton); ActionUtils.configureButton(backAction, backButton); // }); nextGroupAction.disabledProperty().addListener( (ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> { nextButton.setEffect(newValue ? null : DROP_SHADOW); if (newValue == false) { flashAnimation.play(); } else { flashAnimation.stop(); } }); //listen to tile selection and make sure it is visible in scroll area //TODO: make sure we are testing complete visability not just bounds intersection globalSelectionModel.lastSelectedProperty().addListener((observable, oldFileID, newFileId) -> { if (groupViewMode.get() == GroupViewMode.SLIDE_SHOW) { slideShowPane.setFile(newFileId); } else { scrollToFileID(newFileId); } }); setViewState(controller.viewState().get()); }
From source file:org.sleuthkit.autopsy.imagegallery.gui.GroupPane.java
/** * called automatically during constructor by FXMLConstructor. * * checks that FXML loading went ok and performs additional setup *///from www . j a v a2 s . co m @FXML void initialize() { assert gridView != null : "fx:id=\"tilePane\" was not injected: check your FXML file 'GroupPane.fxml'."; assert grpCatSplitMenu != null : "fx:id=\"grpCatSplitMenu\" was not injected: check your FXML file 'GroupHeader.fxml'."; assert grpTagSplitMenu != null : "fx:id=\"grpTagSplitMenu\" was not injected: check your FXML file 'GroupHeader.fxml'."; assert headerToolBar != null : "fx:id=\"headerToolBar\" was not injected: check your FXML file 'GroupHeader.fxml'."; assert segButton != null : "fx:id=\"previewList\" was not injected: check your FXML file 'GroupHeader.fxml'."; assert slideShowToggle != null : "fx:id=\"segButton\" was not injected: check your FXML file 'GroupHeader.fxml'."; assert tileToggle != null : "fx:id=\"tileToggle\" was not injected: check your FXML file 'GroupHeader.fxml'."; //configure flashing glow animation on next unseen group button flashAnimation.setCycleCount(Timeline.INDEFINITE); flashAnimation.setAutoReverse(true); //configure gridView cell properties gridView.cellHeightProperty().bind(Toolbar.getDefault().sizeSliderValue().add(75)); gridView.cellWidthProperty().bind(Toolbar.getDefault().sizeSliderValue().add(75)); gridView.setCellFactory((GridView<Long> param) -> new DrawableCell()); //configure toolbar properties HBox.setHgrow(spacer, Priority.ALWAYS); spacer.setMinWidth(Region.USE_PREF_SIZE); try { grpTagSplitMenu.setText(TagUtils.getFollowUpTagName().getDisplayName()); grpTagSplitMenu.setOnAction(createGrpTagMenuItem(TagUtils.getFollowUpTagName()).getOnAction()); } catch (TskCoreException tskCoreException) { LOGGER.log(Level.WARNING, "failed to load FollowUpTagName", tskCoreException); } grpTagSplitMenu.setGraphic(new ImageView(DrawableAttribute.TAGS.getIcon())); grpTagSplitMenu.showingProperty() .addListener((ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) -> { if (t1) { ArrayList<MenuItem> selTagMenues = new ArrayList<>(); for (final TagName tn : TagUtils.getNonCategoryTagNames()) { MenuItem menuItem = TagUtils.createSelTagMenuItem(tn, grpTagSplitMenu); selTagMenues.add(menuItem); } grpTagSplitMenu.getItems().setAll(selTagMenues); } }); ArrayList<MenuItem> grpCategoryMenues = new ArrayList<>(); for (final Category cat : Category.values()) { MenuItem menuItem = createGrpCatMenuItem(cat); grpCategoryMenues.add(menuItem); } grpCatSplitMenu.setText(Category.FIVE.getDisplayName()); grpCatSplitMenu.setGraphic(new ImageView(DrawableAttribute.CATEGORY.getIcon())); grpCatSplitMenu.getItems().setAll(grpCategoryMenues); grpCatSplitMenu.setOnAction(createGrpCatMenuItem(Category.FIVE).getOnAction()); Runnable syncMode = () -> { switch (groupViewMode.get()) { case SLIDE_SHOW: slideShowToggle.setSelected(true); break; case TILE: tileToggle.setSelected(true); break; } }; syncMode.run(); //make togle states match view state groupViewMode.addListener((o) -> { syncMode.run(); }); slideShowToggle.toggleGroupProperty().addListener((o) -> { slideShowToggle.getToggleGroup().selectedToggleProperty() .addListener((observable, oldToggle, newToggle) -> { if (newToggle == null) { oldToggle.setSelected(true); } }); }); //listen to toggles and update view state slideShowToggle.setOnAction((ActionEvent t) -> { activateSlideShowViewer(globalSelectionModel.lastSelectedProperty().get()); }); tileToggle.setOnAction((ActionEvent t) -> { activateTileViewer(); }); controller.viewState().addListener((ObservableValue<? extends GroupViewState> observable, GroupViewState oldValue, GroupViewState newValue) -> { setViewState(newValue); }); addEventFilter(KeyEvent.KEY_PRESSED, tileKeyboardNavigationHandler); gridView.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { private ContextMenu buildContextMenu() { ArrayList<MenuItem> menuItems = new ArrayList<>(); menuItems.add(CategorizeAction.getPopupMenu()); menuItems.add(AddDrawableTagAction.getInstance().getPopupMenu()); Collection<? extends ContextMenuActionsProvider> menuProviders = Lookup.getDefault() .lookupAll(ContextMenuActionsProvider.class); for (ContextMenuActionsProvider provider : menuProviders) { for (final Action act : provider.getActions()) { if (act instanceof Presenter.Popup) { Presenter.Popup aact = (Presenter.Popup) act; menuItems.add(SwingMenuItemAdapter.create(aact.getPopupPresenter())); } } } final MenuItem extractMenuItem = new MenuItem("Extract File(s)"); extractMenuItem.setOnAction((ActionEvent t) -> { SwingUtilities.invokeLater(() -> { TopComponent etc = WindowManager.getDefault() .findTopComponent(ImageGalleryTopComponent.PREFERRED_ID); ExtractAction.getInstance().actionPerformed(new java.awt.event.ActionEvent(etc, 0, null)); }); }); menuItems.add(extractMenuItem); ContextMenu contextMenu = new ContextMenu(menuItems.toArray(new MenuItem[] {})); contextMenu.setAutoHide(true); return contextMenu; } @Override public void handle(MouseEvent t) { switch (t.getButton()) { case PRIMARY: if (t.getClickCount() == 1) { globalSelectionModel.clearSelection(); if (contextMenu != null) { contextMenu.hide(); } } t.consume(); break; case SECONDARY: if (t.getClickCount() == 1) { selectAllFiles(); } if (globalSelectionModel.getSelected().isEmpty() == false) { if (contextMenu == null) { contextMenu = buildContextMenu(); } contextMenu.hide(); contextMenu.show(GroupPane.this, t.getScreenX(), t.getScreenY()); } t.consume(); break; } } }); ActionUtils.configureButton(nextGroupAction, nextButton); final EventHandler<ActionEvent> onAction = nextButton.getOnAction(); nextButton.setOnAction((ActionEvent event) -> { flashAnimation.stop(); nextButton.setEffect(null); onAction.handle(event); }); ActionUtils.configureButton(forwardAction, forwardButton); ActionUtils.configureButton(backAction, backButton); nextGroupAction.disabledProperty().addListener( (ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) -> { nextButton.setEffect(newValue ? null : DROP_SHADOW); if (newValue == false) { flashAnimation.play(); } else { flashAnimation.stop(); } }); //listen to tile selection and make sure it is visible in scroll area //TODO: make sure we are testing complete visability not just bounds intersection globalSelectionModel.lastSelectedProperty().addListener((observable, oldFileID, newFileId) -> { if (groupViewMode.get() == GroupViewMode.SLIDE_SHOW) { slideShowPane.setFile(newFileId); } else { scrollToFileID(newFileId); } }); setViewState(controller.viewState().get()); }
From source file:calendarioSeries.vistas.MainViewController.java
public void populateImagenes() { Platform.runLater(new Runnable() { @Override/* w w w . j ava 2 s . com*/ public void run() { imagenes.getChildren().clear(); for (Serie serie : series) { //System.out.println(serie.getLastVisto()); try { Image image = new Image(serie.getUrlImagen()); ImageView poster = new ImageView(); ContextMenu menu = new ContextMenu(); //String css = MainApp.class.getResource("resources/MainTheme.css").toExternalForm(); MenuItem delete = new MenuItem("Eliminar"); delete.setId(serie.getId()); delete.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { menu.hide(); MenuItem clicked = (MenuItem) event.getSource(); String toDelete = clicked.getId(); for (Serie serie : series) { if (serie.getId().equals(toDelete)) { series.remove(serie); populateImagenes(); showDetallesMes(mesActual); } } event.consume(); } }); menu.getItems().add(delete); poster.setId(serie.getTitulo()); poster.setImage(image); poster.setCache(true); // poster.setPreserveRatio(true); poster.setFitWidth(210); poster.setFitHeight(300); poster.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() { @Override public void handle(ContextMenuEvent event) { menu.show(poster, event.getScreenX(), event.getScreenY()); //menu.getScene().getRoot().getStylesheets().add(css); event.consume(); } }); poster.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.getButton() == MouseButton.PRIMARY) { try { //serieToPass = serie; sceneToPass = mainApp.scene; FXMLLoader loader = new FXMLLoader( getClass().getResource("DetailsSerieController.fxml")); Parent root = loader.load(); DetailsSerieController controller = loader.getController(); controller.setData(serie, series); controller.setMainApp(mainApp); Scene scene = new Scene(root); mainApp.primaryStage.setScene(scene); mainApp.primaryStage.show(); } catch (IOException ex) { ex.printStackTrace(); } } } }); imagenes.getChildren().add(poster); } catch (IllegalArgumentException e) { Image image = new Image("file:src/calendarioSeries/resources/no-image.png"); ImageView poster = new ImageView(); ContextMenu menu = new ContextMenu(); MenuItem delete = new MenuItem("Eliminar"); delete.setId(serie.getId()); delete.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { menu.hide(); MenuItem clicked = (MenuItem) event.getSource(); String toDelete = clicked.getId(); for (Serie serie : series) { if (serie.getId().equals(toDelete)) { series.remove(serie); populateImagenes(); showDetallesMes(mesActual); } } event.consume(); } }); menu.getItems().add(delete); poster.setId(serie.getTitulo()); poster.setImage(image); poster.setCache(true); //poster.setPreserveRatio(true); poster.setFitWidth(210); poster.setFitHeight(300); poster.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() { @Override public void handle(ContextMenuEvent event) { menu.show(poster, event.getScreenX(), event.getScreenY()); event.consume(); } }); Text text = new Text(serie.getTitulo()); text.getStyleClass().add("label"); StackPane pane = new StackPane(); pane.getChildren().addAll(poster, text); imagenes.getChildren().add(pane); } finally { rellenarArchivo(); } } } }); }
From source file:View.Visualize.java
private void addColorChangeOnSeries(XYChart.Series series) { final ContextMenu contextMenu = new ContextMenu(); MenuItem changeColor = new MenuItem("Change color"); MenuItem delete = new MenuItem("Standard color"); ColorPicker cp = new ColorPicker(); changeColor.setGraphic(cp);//from w ww . j a va 2 s . c om contextMenu.getItems().addAll(changeColor, delete); Node d = series.getNode(); d.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent t) { if (t.getButton() == MouseButton.SECONDARY) { delete.setOnAction(new EventHandler() { public void handle(Event t) { if (series.getChart() instanceof StackedAreaChart) { series.getChart().lookup(".default-color" + series.getNode().getUserData() + ".chart-series-area-fill").setStyle(""); } if (series.getChart() instanceof LineChart) { series.getChart().lookup( ".default-color" + series.getNode().getUserData() + ".chart-series-line") .setStyle(""); } } }); cp.setValue(null); cp.setOnAction(new EventHandler() { public void handle(Event t) { String hex1 = "#" + Integer.toHexString(cp.getValue().hashCode()); if (series.getChart() instanceof StackedAreaChart) { series.getChart().lookup(".default-color" + series.getNode().getUserData() + ".chart-series-area-fill").setStyle("-fx-fill:" + hex1 + ";"); } if (series.getChart() instanceof LineChart) { series.getChart().lookup( ".default-color" + series.getNode().getUserData() + ".chart-series-line") .setStyle("-fx-stroke:" + hex1 + ";"); } } }); contextMenu.show(d, t.getScreenX(), t.getScreenY()); } } }); }
From source file:com.ggvaidya.scinames.dataset.BinomialChangesSceneController.java
private void setupTableWithBinomialChanges() { changesTableView.setEditable(false); changesTableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); changesTableView.setItems(potentialChanges); changesTableView.getColumns().clear(); TableColumn<PotentialChange, ChangeType> colChangeType = new TableColumn<>("Type"); colChangeType.setCellFactory(ComboBoxTableCell.forTableColumn(new ChangeTypeStringConverter(), ChangeType.ADDITION, ChangeType.DELETION, ChangeType.RENAME, ChangeType.LUMP, ChangeType.SPLIT, ChangeType.COMPLEX, ChangeType.ERROR)); colChangeType.setCellValueFactory(new PropertyValueFactory<>("type")); colChangeType.setPrefWidth(100.0);//from ww w .j a va2 s. c o m colChangeType.setEditable(true); changesTableView.getColumns().add(colChangeType); TableColumn<PotentialChange, ObservableSet<Name>> colChangeFrom = new TableColumn<>("From"); colChangeFrom.setCellFactory(TextFieldTableCell.forTableColumn(new NameSetStringConverter())); colChangeFrom.setCellValueFactory(new PropertyValueFactory<>("from")); colChangeFrom.setPrefWidth(200.0); colChangeFrom.setEditable(true); changesTableView.getColumns().add(colChangeFrom); TableColumn<PotentialChange, ObservableSet<Name>> colChangeTo = new TableColumn<>("To"); colChangeTo.setCellFactory(TextFieldTableCell.forTableColumn(new NameSetStringConverter())); colChangeTo.setCellValueFactory(new PropertyValueFactory<>("to")); colChangeTo.setPrefWidth(200.0); colChangeTo.setEditable(true); changesTableView.getColumns().add(colChangeTo); TableColumn<PotentialChange, String> colDataset = new TableColumn<>("Dataset"); colDataset.setCellValueFactory(cvf -> { return new ReadOnlyStringWrapper(cvf.getValue().getDataset().toString()); }); colDataset.setPrefWidth(150.0); changesTableView.getColumns().add(colDataset); TableColumn<PotentialChange, SimplifiedDate> dateCol = new TableColumn<>("Date"); dateCol.setCellFactory( TextFieldTableCell.forTableColumn(new SimplifiedDate.SimplifiedDateStringConverter())); dateCol.setCellValueFactory(cvf -> new ReadOnlyObjectWrapper<>(cvf.getValue().getDataset().getDate())); dateCol.setPrefWidth(150); dateCol.setSortable(true); dateCol.setSortType(SortType.ASCENDING); changesTableView.getColumns().add(dateCol); changesTableView.getSortOrder().add(dateCol); TableColumn<PotentialChange, String> colChangeSummary = new TableColumn<>("Changes summary"); colChangeSummary.setCellValueFactory(cvf -> { Set<Change> changes = changesByPotentialChange.get(cvf.getValue()); return new ReadOnlyStringWrapper(changes.size() + ": " + changes.stream().map(ch -> ch.toString()).collect(Collectors.joining("; "))); }); colChangeSummary.setPrefWidth(200.0); changesTableView.getColumns().add(colChangeSummary); /* TableColumn<PotentialChange, String> colExplicit = new TableColumn<>("Explicit or implicit?"); colExplicit.setCellValueFactory( (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper( features.getValue().getDataset().isChangeImplicit(features.getValue()) ? "Implicit" : "Explicit" ) ); tv.getColumns().add(colExplicit); ChangeFilter cf = binomialChangesView.getProjectView().getProject().getChangeFilter(); TableColumn<Change, String> colFiltered = new TableColumn<>("Eliminated by filter?"); colFiltered.setCellValueFactory( (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper( cf.test(features.getValue()) ? "Allowed" : "Eliminated" ) ); tv.getColumns().add(colFiltered); */ TableColumn<PotentialChange, String> colNote = new TableColumn<>("Note"); colNote.setCellFactory(TextFieldTableCell.forTableColumn()); colNote.setCellValueFactory(new PropertyValueFactory<>("note")); colNote.setPrefWidth(100.0); changesTableView.getColumns().add(colNote); TableColumn<PotentialChange, String> colReason = new TableColumn<>("Reason"); colReason.setCellValueFactory(cvf -> new ReadOnlyStringWrapper(calculateReason(cvf.getValue()))); colReason.setPrefWidth(100.0); changesTableView.getColumns().add(colReason); TableColumn<PotentialChange, String> colReasonDate = new TableColumn<>("ReasonDate"); colReasonDate.setCellValueFactory(cvf -> { String result; Set<SimplifiedDate> dates = calculateReasonDate(cvf.getValue()); if (dates.size() > 1) { result = "(" + dates.size() + ") " + dates.stream().distinct().sorted() .map(sd -> sd.asYYYYmmDD("-")).collect(Collectors.joining("|")); } else if (dates.size() == 1) { result = dates.iterator().next().asYYYYmmDD("-"); } else { result = "NA"; } return new ReadOnlyStringWrapper(result); }); colReasonDate.setPrefWidth(100.0); changesTableView.getColumns().add(colReasonDate); TableColumn<PotentialChange, String> colCitations = new TableColumn<>("Citations"); colCitations.setCellValueFactory( (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper( features.getValue().getCitationStream().map(citation -> citation.getCitation()).sorted() .collect(Collectors.joining("; ")))); changesTableView.getColumns().add(colCitations); TableColumn<PotentialChange, String> colGenera = new TableColumn<>("Genera"); colGenera.setCellValueFactory( (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper( String.join(", ", features.getValue().getAllNames().stream().map(n -> n.getGenus()) .distinct().sorted().collect(Collectors.toList())))); changesTableView.getColumns().add(colGenera); TableColumn<PotentialChange, String> colSpecificEpithet = new TableColumn<>("Specific epithets"); colSpecificEpithet.setCellValueFactory( (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper(String .join(", ", features.getValue().getAllNames().stream().map(n -> n.getSpecificEpithet()) .filter(s -> s != null).distinct().sorted().collect(Collectors.toList())))); changesTableView.getColumns().add(colSpecificEpithet); // The infraspecific string. TableColumn<PotentialChange, String> colInfraspecificEpithet = new TableColumn<>("Infraspecific epithets"); colInfraspecificEpithet.setCellValueFactory( (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper( String.join(", ", features.getValue().getAllNames().stream() .map(n -> n.getInfraspecificEpithetsAsString()).filter(s -> s != null) .distinct().sorted().collect(Collectors.toList())))); changesTableView.getColumns().add(colInfraspecificEpithet); // The very last epithet of all TableColumn<PotentialChange, String> colTerminalEpithet = new TableColumn<>("Terminal epithet"); colTerminalEpithet.setCellValueFactory( (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper( String.join(", ", features.getValue().getAllNames().stream().map(n -> { List<Name.InfraspecificEpithet> infraspecificEpithets = n.getInfraspecificEpithets(); if (!infraspecificEpithets.isEmpty()) { return infraspecificEpithets.get(infraspecificEpithets.size() - 1).getValue(); } else { return n.getSpecificEpithet(); } }).filter(s -> s != null).distinct().sorted().collect(Collectors.toList())))); changesTableView.getColumns().add(colTerminalEpithet); TableColumn<PotentialChange, String> dateForRCol = new TableColumn<>("DateYMD"); dateForRCol.setCellValueFactory( cvf -> new ReadOnlyObjectWrapper<>(cvf.getValue().getDataset().getDate().asYYYYmmDD("-"))); changesTableView.getColumns().add(dateForRCol); // Properties TableColumn<PotentialChange, String> colProperties = new TableColumn<>("Properties"); colProperties.setCellValueFactory( (TableColumn.CellDataFeatures<PotentialChange, String> features) -> new ReadOnlyStringWrapper( features.getValue().getProperties().entrySet().stream() .map(entry -> entry.getKey() + ": " + entry.getValue()).sorted() .collect(Collectors.joining("; ")))); changesTableView.getColumns().add(colProperties); fillTableWithBinomialChanges(); // When someone selects a cell in the Table, try to select the appropriate data in the // additional data view. changesTableView.getSelectionModel().getSelectedItems() .addListener((ListChangeListener<PotentialChange>) lcl -> { AdditionalData aData = additionalDataCombobox.getSelectionModel().getSelectedItem(); if (aData != null) { aData.onSelectChange(changesTableView.getSelectionModel().getSelectedItems()); } }); // Create a right-click menu for table rows. changesTableView.setRowFactory(table -> { TableRow<PotentialChange> row = new TableRow<>(); row.setOnContextMenuRequested(event -> { if (row.isEmpty()) return; // We don't currently use the clicked change, since currently all options // change *all* the selected changes, but this may change in the future. PotentialChange change = row.getItem(); ContextMenu changeMenu = new ContextMenu(); Menu lookupChange = new Menu("Look up change"); lookupChange.getItems().addAll(changesByPotentialChange.getOrDefault(change, new HashSet<>()) .stream() .map(ch -> createMenuItem(ch.toString() + " in " + ch.getDataset().toString(), action -> { binomialChangesView.getProjectView().openDetailedView(ch); })).collect(Collectors.toList())); changeMenu.getItems().add(lookupChange); changeMenu.getItems().add(new SeparatorMenuItem()); Menu searchForName = new Menu("Search for name"); searchForName.getItems().addAll( change.getAllNames().stream().sorted().map(n -> createMenuItem(n.getFullName(), action -> { binomialChangesView.getProjectView().openDetailedView(n); })).collect(Collectors.toList())); changeMenu.getItems().add(searchForName); changeMenu.getItems().add(new SeparatorMenuItem()); // Create a submenu for tags and urls. String note = change.noteProperty().get(); Menu removeTags = new Menu("Tags"); removeTags.getItems().addAll(change.getTags().stream().sorted() .map(tag -> new MenuItem(tag.getName())).collect(Collectors.toList())); Menu lookupURLs = new Menu("Lookup URL"); change.getURIs().stream().sorted().map(uri -> { return createMenuItem(uri.toString(), evt -> { try { Desktop.getDesktop().browse(uri); } catch (IOException ex) { LOGGER.warning("Could not open URL '" + uri + "': " + ex); } }); }).forEach(mi -> lookupURLs.getItems().add(mi)); changeMenu.getItems().add(lookupURLs); changeMenu.show(binomialChangesView.getScene().getWindow(), event.getScreenX(), event.getScreenY()); }); return row; }); LOGGER.info("setupTableWithChanges() completed"); }
From source file:qupath.lib.gui.panels.survival.KaplanMeierDisplay.java
@SuppressWarnings("unchecked") private void generatePlot() { KaplanMeierDisplay.ScoreData newScoreData = scoreData; // If we have a hierarchy, update the scores with the most recent data if (hierarchy != null) { List<TMACoreObject> cores = PathObjectTools.getTMACoreObjects(hierarchy, false); double[] survival = new double[cores.size()]; boolean[] censored = new boolean[cores.size()]; double[] scores = new double[cores.size()]; // // Optionally sort by scores... helps a bit when debugging e.g. p-values, Hazard ratios etc. // cores.sort((c1, c2) -> Double.compare(c1.getMeasurementList().getMeasurementValue(scoreColumn), c2.getMeasurementList().getMeasurementValue(scoreColumn))); // scoreColumn = "Positive %"; // scoreColumn = "RoughScore"; for (int i = 0; i < cores.size(); i++) { TMACoreObject core = cores.get(i); MeasurementList ml = core.getMeasurementList(); survival[i] = core.getMeasurementList().getMeasurementValue(survivalColumn); double censoredValue = core.getMeasurementList().getMeasurementValue(censoredColumn); boolean hasCensoredValue = !Double.isNaN(censoredValue) && (censoredValue == 0 || censoredValue == 1); censored[i] = censoredValue != 0; if (!hasCensoredValue) { // If we don't have a censored value, ensure we mask out everything else scores[i] = Double.NaN; survival[i] = Double.NaN; } else if (ml.containsNamedMeasurement(scoreColumn)) // Get the score if we can scores[i] = ml.getMeasurementValue(scoreColumn); else { // // Try to compute score if we need to // Map<String, Number> map = ROIMeaningfulMeasurements.getPathClassSummaryMeasurements(core.getChildObjects(), true); // Number value = map.get(scoreColumn); // if (value == null) scores[i] = Double.NaN; // else // scores[i] = value.doubleValue(); }//from ww w. ja va2 s. c om } // Mask out any scores that don't have associated survival data for (int i = 0; i < survival.length; i++) { if (Double.isNaN(survival[i])) scores[i] = Double.NaN; } newScoreData = new ScoreData(scores, survival, censored); } if (newScoreData == null || newScoreData.scores.length == 0) return; // KaplanMeier kmHigh = new KaplanMeier("Above threshold"); // KaplanMeier kmLow = new KaplanMeier("Below threshold"); double[] quartiles = StatisticsHelper.getQuartiles(newScoreData.scores); double q1 = quartiles[0]; double median = quartiles[1]; double q3 = quartiles[2]; double[] thresholds; if (params != null) { Object thresholdMethod = params.getChoiceParameterValue("scoreThresholdMethod"); if (thresholdMethod.equals("Median")) { // panelParams.setNumericParameterValue("scoreThreshold", median); // ((DoubleParameter)params.getParameters().get("scoreThreshold")).setValue(median); // TODO: UPDATE DIALOG! thresholds = new double[] { median }; } else if (thresholdMethod.equals("Tertiles")) { // ((DoubleParameter)params.getParameters().get("scoreThreshold")).setValue(median); // TODO: UPDATE DIALOG! thresholds = StatisticsHelper.getTertiles(newScoreData.scores); } else if (thresholdMethod.equals("Quartiles")) { // ((DoubleParameter)params.getParameters().get("scoreThreshold")).setValue(median); // TODO: UPDATE DIALOG! thresholds = new double[] { q1, median, q3 }; } else if (thresholdMethod.equals("Manual (1)")) { thresholds = new double[] { params.getDoubleParameterValue("threshold1") }; } else if (thresholdMethod.equals("Manual (2)")) { thresholds = new double[] { params.getDoubleParameterValue("threshold1"), params.getDoubleParameterValue("threshold2") }; } else //if (thresholdMethod.equals("Manual (3)")) { thresholds = new double[] { params.getDoubleParameterValue("threshold1"), params.getDoubleParameterValue("threshold2"), params.getDoubleParameterValue("threshold3") }; } else thresholds = new double[] { median }; double minVal = Double.POSITIVE_INFINITY; double maxVal = Double.NEGATIVE_INFINITY; int numNonNaN = 0; for (double d : newScoreData.scores) { if (Double.isNaN(d)) continue; if (d < minVal) minVal = d; if (d > maxVal) maxVal = d; numNonNaN++; } boolean scoresValid = maxVal > minVal; // If not this, we don't have valid scores that we can work with double maxTimePoint = 0; for (double d : newScoreData.survival) { if (Double.isNaN(d)) continue; if (d > maxTimePoint) maxTimePoint = d; } if (panelParams != null && maxTimePoint > ((IntParameter) params.getParameters().get("censorTimePoints")).getUpperBound()) { panelParams.setNumericParameterValueRange("censorTimePoints", 0, Math.ceil(maxTimePoint)); } // Optionally censor at specified time double censorThreshold = params == null ? maxTimePoint : params.getIntParameterValue("censorTimePoints"); // Compute log-rank p-values for *all* possible thresholds // Simultaneously determine the threshold that yields the lowest p-value, // resolving ties in favour of a more even split between high/low numbers of events boolean pValuesChanged = false; if (calculateAllPValues) { if (!(pValues != null && pValueThresholds != null && newScoreData.equals(scoreData) && censorThreshold == lastPValueCensorThreshold)) { Map<Double, Double> mapLogRank = new TreeMap<>(); Set<Double> setObserved = new HashSet<>(); for (int i = 0; i < newScoreData.scores.length; i++) { Double d = newScoreData.scores[i]; boolean observed = !newScoreData.censored[i] && newScoreData.survival[i] < censorThreshold; if (observed) setObserved.add(d); if (mapLogRank.containsKey(d)) continue; List<KaplanMeierData> kmsTemp = splitByThresholds(newScoreData, new double[] { d }, censorThreshold, false); // if (kmsTemp.get(1).nObserved() == 0 || kmsTemp.get(1).nObserved() == 0) // continue; LogRankResult test = LogRankTest.computeLogRankTest(kmsTemp.get(0), kmsTemp.get(1)); double pValue = test.getPValue(); // double pValue = test.hazardRatio < 1 ? test.hazardRatio : 1.0/test.hazardRatio; // Checking usefulness of Hazard ratios... if (!Double.isFinite(pValue)) continue; // if (!Double.isFinite(test.getHazardRatio())) { //// continue; // pValue = Double.NaN; // } mapLogRank.put(d, pValue); } pValueThresholds = new double[mapLogRank.size()]; pValues = new double[mapLogRank.size()]; pValueThresholdsObserved = new boolean[mapLogRank.size()]; int count = 0; for (Entry<Double, Double> entry : mapLogRank.entrySet()) { pValueThresholds[count] = entry.getKey(); pValues[count] = entry.getValue(); if (setObserved.contains(entry.getKey())) pValueThresholdsObserved[count] = true; count++; } // Find the longest 'significant' stretch int maxSigCount = 0; int maxSigInd = -1; int sigCurrent = 0; int[] sigCount = new int[pValues.length]; for (int i = 0; i < pValues.length; i++) { if (pValues[i] < 0.05) { sigCurrent++; sigCount[i] = sigCurrent; if (sigCurrent > maxSigCount) { maxSigCount = sigCurrent; maxSigInd = i; } } else sigCurrent = 0; } if (maxSigCount == 0) { logger.info("No p-values < 0.05"); } else { double minThresh = maxSigInd - maxSigCount < 0 ? pValueThresholds[0] - 0.0000001 : pValueThresholds[maxSigInd - maxSigCount]; double maxThresh = pValueThresholds[maxSigInd]; int nBetween = 0; int nBetweenObserved = 0; for (int i = 0; i < newScoreData.scores.length; i++) { if (newScoreData.scores[i] > minThresh && newScoreData.scores[i] <= maxThresh) { nBetween++; if (newScoreData.survival[i] < censorThreshold && !newScoreData.censored[i]) nBetweenObserved++; } } logger.info("Longest stretch of p-values < 0.05: {} - {} ({} entries, {} observed)", minThresh, maxThresh, nBetween, nBetweenObserved); } pValuesSmoothed = new double[pValues.length]; Arrays.fill(pValuesSmoothed, Double.NaN); int n = (pValues.length / 20) * 2 + 1; logger.info("Smoothing log-rank test p-values by " + n); for (int i = n / 2; i < pValues.length - n / 2; i++) { double sum = 0; for (int k = i - n / 2; k < i - n / 2 + n; k++) { sum += pValues[k]; } pValuesSmoothed[i] = sum / n; } // for (int i = 0; i < pValues.length; i++) { // double sum = 0; // for (int k = Math.max(0, i-n/2); k < Math.min(pValues.length, i-n/2+n); k++) { // sum += pValues[k]; // } // pValuesSmoothed[i] = sum/n; // } // pValues = pValuesSmoothed; lastPValueCensorThreshold = censorThreshold; pValuesChanged = true; } } else { lastPValueCensorThreshold = Double.NaN; pValueThresholds = null; pValues = null; } // if (params != null && !Double.isNaN(bestThreshold) && (params.getChoiceParameterValue("scoreThresholdMethod").equals("Lowest p-value"))) if (params != null && (params.getChoiceParameterValue("scoreThresholdMethod").equals("Lowest p-value"))) { int bestIdx = -1; double bestPValue = Double.POSITIVE_INFINITY; for (int i = pValueThresholds.length / 10; i < pValueThresholds.length * 9 / 10; i++) { if (pValues[i] < bestPValue) { bestIdx = i; bestPValue = pValues[i]; } } thresholds = bestIdx >= 0 ? new double[] { pValueThresholds[bestIdx] } : new double[0]; } else if (params != null && (params.getChoiceParameterValue("scoreThresholdMethod").equals("Lowest smoothed p-value"))) { int bestIdx = -1; double bestPValue = Double.POSITIVE_INFINITY; for (int i = pValueThresholds.length / 10; i < pValueThresholds.length * 9 / 10; i++) { if (pValuesSmoothed[i] < bestPValue) { bestIdx = i; bestPValue = pValuesSmoothed[i]; } } thresholds = bestIdx >= 0 ? new double[] { pValueThresholds[bestIdx] } : new double[0]; } // Split into different curves using the provided thresholds List<KaplanMeierData> kms = splitByThresholds(newScoreData, thresholds, censorThreshold, params != null && "Quartiles".equals(params.getChoiceParameterValue("scoreThresholdMethod"))); // for (KaplanMeier km : kms) // km.censorAtTime(censorThreshold); //// kmHigh.censorAtTime(censorThreshold); //// kmLow.censorAtTime(censorThreshold); // logger.info("High: " + kmHigh.toString()); // logger.info("Low: " + kmLow.toString()); // logger.info("Log rank comparison: {}", LogRankTest.computeLogRankTest(kmLow, kmHigh)); if (plotter == null) { plotter = new KaplanMeierChartWrapper(survivalColumn + " time"); // plotter.setBorder(BorderFactory.createTitledBorder("Survival plot")); // plotter.getCanvas().setWidth(300); // plotter.getCanvas().setHeight(300); } KaplanMeierData[] kmArray = new KaplanMeierData[kms.size()]; plotter.setKaplanMeierCurves(survivalColumn + " time", kms.toArray(kmArray)); tableModel.setSurvivalCurves(thresholds, params != null && params.getChoiceParameterValue("scoreThresholdMethod").equals("Lowest p-value"), kmArray); // Bar width determined using 'Freedman and Diaconis' rule' (but overridden if this gives < 16 bins...) double barWidth = (2 * q3 - q1) * Math.pow(numNonNaN, -1.0 / 3.0); int nBins = 100; if (!Double.isNaN(barWidth)) barWidth = (int) Math.max(16, Math.ceil((maxVal - minVal) / barWidth)); Histogram histogram = scoresValid ? new Histogram(newScoreData.scores, nBins) : null; if (histogramPanel == null) { GridPane paneHistogram = new GridPane(); histogramPanel = new HistogramPanelFX(); histogramPanel.getChart().setAnimated(false); histogramWrapper = new ThresholdedChartWrapper(histogramPanel.getChart()); for (ObservableNumberValue val : threshProperties) histogramWrapper.addThreshold(val, ColorToolsFX.getCachedColor(240, 0, 0, 128)); histogramWrapper.getPane().setPrefHeight(150); paneHistogram.add(histogramWrapper.getPane(), 0, 0); Tooltip.install(histogramPanel.getChart(), new Tooltip("Distribution of scores")); GridPane.setHgrow(histogramWrapper.getPane(), Priority.ALWAYS); GridPane.setVgrow(histogramWrapper.getPane(), Priority.ALWAYS); NumberAxis xAxis = new NumberAxis(); xAxis.setLabel("Score threshold"); NumberAxis yAxis = new NumberAxis(); yAxis.setLowerBound(0); yAxis.setUpperBound(1); yAxis.setTickUnit(0.1); yAxis.setAutoRanging(false); yAxis.setLabel("P-value"); chartPValues = new LineChart<>(xAxis, yAxis); chartPValues.setAnimated(false); chartPValues.setLegendVisible(false); // Make chart so it can be navigated ChartToolsFX.makeChartInteractive(chartPValues, xAxis, yAxis); pValuesChanged = true; Tooltip.install(chartPValues, new Tooltip( "Distribution of p-values (log-rank test) comparing low vs. high for all possible score thresholds")); // chartPValues.getYAxis().setAutoRanging(false); pValuesWrapper = new ThresholdedChartWrapper(chartPValues); for (ObservableNumberValue val : threshProperties) pValuesWrapper.addThreshold(val, ColorToolsFX.getCachedColor(240, 0, 0, 128)); pValuesWrapper.getPane().setPrefHeight(150); paneHistogram.add(pValuesWrapper.getPane(), 0, 1); GridPane.setHgrow(pValuesWrapper.getPane(), Priority.ALWAYS); GridPane.setVgrow(pValuesWrapper.getPane(), Priority.ALWAYS); ContextMenu popup = new ContextMenu(); ChartToolsFX.addChartExportMenu(chartPValues, popup); RadioMenuItem miZoomY1 = new RadioMenuItem("0-1"); miZoomY1.setOnAction(e -> { yAxis.setAutoRanging(false); yAxis.setUpperBound(1); yAxis.setTickUnit(0.2); }); RadioMenuItem miZoomY05 = new RadioMenuItem("0-0.5"); miZoomY05.setOnAction(e -> { yAxis.setAutoRanging(false); yAxis.setUpperBound(0.5); yAxis.setTickUnit(0.1); }); RadioMenuItem miZoomY02 = new RadioMenuItem("0-0.2"); miZoomY02.setOnAction(e -> { yAxis.setAutoRanging(false); yAxis.setUpperBound(0.2); yAxis.setTickUnit(0.05); }); RadioMenuItem miZoomY01 = new RadioMenuItem("0-0.1"); miZoomY01.setOnAction(e -> { yAxis.setAutoRanging(false); yAxis.setUpperBound(0.1); yAxis.setTickUnit(0.05); }); RadioMenuItem miZoomY005 = new RadioMenuItem("0-0.05"); miZoomY005.setOnAction(e -> { yAxis.setAutoRanging(false); yAxis.setUpperBound(0.05); yAxis.setTickUnit(0.01); }); RadioMenuItem miZoomY001 = new RadioMenuItem("0-0.01"); miZoomY001.setOnAction(e -> { yAxis.setAutoRanging(false); yAxis.setUpperBound(0.01); yAxis.setTickUnit(0.005); }); ToggleGroup tgZoom = new ToggleGroup(); miZoomY1.setToggleGroup(tgZoom); miZoomY05.setToggleGroup(tgZoom); miZoomY02.setToggleGroup(tgZoom); miZoomY01.setToggleGroup(tgZoom); miZoomY005.setToggleGroup(tgZoom); miZoomY001.setToggleGroup(tgZoom); Menu menuZoomY = new Menu("Set y-axis range"); menuZoomY.getItems().addAll(miZoomY1, miZoomY05, miZoomY02, miZoomY01, miZoomY005, miZoomY001); MenuItem miCopyData = new MenuItem("Copy chart data"); miCopyData.setOnAction(e -> { String dataString = ChartToolsFX.getChartDataAsString(chartPValues); ClipboardContent content = new ClipboardContent(); content.putString(dataString); Clipboard.getSystemClipboard().setContent(content); }); popup.getItems().addAll(miCopyData, menuZoomY); chartPValues.setOnContextMenuRequested(e -> { popup.show(chartPValues, e.getScreenX(), e.getScreenY()); }); for (int col = 0; col < tableModel.getColumnCount(); col++) { TableColumn<Integer, String> column = new TableColumn<>(tableModel.getColumnName(col)); int colNumber = col; column.setCellValueFactory( new Callback<CellDataFeatures<Integer, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(CellDataFeatures<Integer, String> p) { return new SimpleStringProperty( (String) tableModel.getValueAt(p.getValue(), colNumber)); } }); column.setCellFactory(new Callback<TableColumn<Integer, String>, TableCell<Integer, String>>() { @Override public TableCell<Integer, String> call(TableColumn<Integer, String> param) { TableCell<Integer, String> cell = new TableCell<Integer, String>() { @Override protected void updateItem(String item, boolean empty) { super.updateItem(item, empty); setText(item); setTooltip(new Tooltip(item)); } }; return cell; } }); table.getColumns().add(column); } table.setPrefHeight(250); table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); table.maxHeightProperty().bind(table.prefHeightProperty()); params = new ParameterList(); // maxTimePoint = 0; // for (TMACoreObject core : hierarchy.getTMAGrid().getTMACoreList()) { // double os = core.getMeasurementList().getMeasurementValue(TMACoreObject.KEY_OVERALL_SURVIVAL); // double rfs = core.getMeasurementList().getMeasurementValue(TMACoreObject.KEY_RECURRENCE_FREE_SURVIVAL); // if (os > maxTimePoint) // maxTimePoint = os; // if (rfs > maxTimePoint) // maxTimePoint = rfs; // } params.addIntParameter("censorTimePoints", "Max censored time", (int) (censorThreshold + 0.5), null, 0, (int) Math.ceil(maxTimePoint), "Latest time point beyond which data will be censored"); // params.addChoiceParameter("scoreThresholdMethod", "Threshold method", "Manual", Arrays.asList("Manual", "Median", "Log-rank test")); if (calculateAllPValues) // Don't include "Lowest smoothed p-value" - it's not an established method and open to misinterpretation... params.addChoiceParameter("scoreThresholdMethod", "Threshold method", "Median", Arrays.asList("Manual (1)", "Manual (2)", "Manual (3)", "Median", "Tertiles", "Quartiles", "Lowest p-value")); // params.addChoiceParameter("scoreThresholdMethod", "Threshold method", "Median", Arrays.asList("Manual (1)", "Manual (2)", "Manual (3)", "Median", "Tertiles", "Quartiles", "Lowest p-value", "Lowest smoothed p-value")); else params.addChoiceParameter("scoreThresholdMethod", "Threshold method", "Median", Arrays.asList("Manual (1)", "Manual (2)", "Manual (3)", "Median", "Tertiles", "Quartiles")); params.addDoubleParameter("threshold1", "Threshold 1", thresholds.length > 0 ? thresholds[0] : (minVal + maxVal) / 2, null, "Threshold to distinguish between patient groups"); params.addDoubleParameter("threshold2", "Threshold 2", thresholds.length > 1 ? thresholds[1] : (minVal + maxVal) / 2, null, "Threshold to distinguish between patient groups"); params.addDoubleParameter("threshold3", "Threshold 3", thresholds.length > 2 ? thresholds[2] : (minVal + maxVal) / 2, null, "Threshold to distinguish between patient groups"); params.addBooleanParameter("showAtRisk", "Show at risk", plotter.getShowAtRisk(), "Show number of patients at risk below the plot"); params.addBooleanParameter("showTicks", "Show censored ticks", plotter.getShowCensoredTicks(), "Show ticks to indicate censored data"); params.addBooleanParameter("showKey", "Show key", plotter.getShowKey(), "Show key indicating display of each curve"); // params.addBooleanParameter("useColor", "Use color", plotter.getUseColor(), "Show each curve in a different color"); // params.addBooleanParameter("useStrokes", "Use strokes", plotter.getUseStrokes(), "Show each curve with a differed line stroke"); // Hide threshold parameters if threshold can't be used if (!scoresValid) { // params.setHiddenParameters(true, "scoreThresholdMethod", "scoreThreshold"); histogramPanel.getChart().setVisible(false); } panelParams = new ParameterPanelFX(params); panelParams.addParameterChangeListener(this); updateThresholdsEnabled(); for (int i = 0; i < threshProperties.length; i++) { String p = "threshold" + (i + 1); threshProperties[i].addListener((v, o, n) -> { if (interactiveThresholds()) { // Need to do a decent double check with tolerance to text field value changing while typing if (!GeneralTools.almostTheSame(params.getDoubleParameterValue(p), n.doubleValue(), 0.0001)) panelParams.setNumericParameterValue(p, n); } }); } BorderPane paneBottom = new BorderPane(); TitledPane paneOptions = new TitledPane("Options", panelParams.getPane()); // paneOptions.setCollapsible(false); Pane paneCanvas = new StackPane(); paneCanvas.getChildren().add(plotter.getCanvas()); GridPane paneLeft = new GridPane(); paneLeft.add(paneOptions, 0, 0); paneLeft.add(table, 0, 1); GridPane.setHgrow(paneOptions, Priority.ALWAYS); GridPane.setHgrow(table, Priority.ALWAYS); paneBottom.setLeft(paneLeft); paneBottom.setCenter(paneHistogram); paneMain.setCenter(paneCanvas); paneMain.setBottom(paneBottom); paneMain.setPadding(new Insets(10, 10, 10, 10)); } else if (thresholds.length > 0) { // Ensure the sliders/text fields are set sensibly if (!GeneralTools.almostTheSame(thresholds[0], params.getDoubleParameterValue("threshold1"), 0.0001)) { panelParams.setNumericParameterValue("threshold1", thresholds[0]); } if (thresholds.length > 1 && !GeneralTools.almostTheSame(thresholds[1], params.getDoubleParameterValue("threshold2"), 0.0001)) { panelParams.setNumericParameterValue("threshold2", thresholds[1]); } if (thresholds.length > 2 && !GeneralTools.almostTheSame(thresholds[2], params.getDoubleParameterValue("threshold3"), 0.0001)) { panelParams.setNumericParameterValue("threshold3", thresholds[2]); } } if (histogram != null) { histogramPanel.getHistogramData() .setAll(HistogramPanelFX.createHistogramData(histogram, false, (Color) null)); histogramPanel.getChart().getXAxis().setLabel(scoreColumn); histogramPanel.getChart().getYAxis().setLabel("Count"); ChartToolsFX.addChartExportMenu(histogramPanel.getChart(), null); // histogramWrapper.setVerticalLines(thresholds, ColorToolsFX.getCachedColor(240, 0, 0, 128)); // Deal with threshold adjustment // histogramWrapper.getThresholds().addListener((Observable o) -> generatePlot()); } if (pValues != null) { // TODO: Raise earlier where p-value calculation is if (pValuesChanged) { ObservableList<XYChart.Data<Number, Number>> data = FXCollections.observableArrayList(); for (int i = 0; i < pValueThresholds.length; i++) { double pValue = pValues[i]; if (Double.isNaN(pValue)) continue; data.add(new XYChart.Data<>(pValueThresholds[i], pValue, pValueThresholdsObserved[i])); } ObservableList<XYChart.Data<Number, Number>> dataSmoothed = null; if (pValuesSmoothed != null) { dataSmoothed = FXCollections.observableArrayList(); for (int i = 0; i < pValueThresholds.length; i++) { double pValueSmoothed = pValuesSmoothed[i]; if (Double.isNaN(pValueSmoothed)) continue; dataSmoothed.add(new XYChart.Data<>(pValueThresholds[i], pValueSmoothed)); } } // Don't bother showing the smoothed data... it tends to get in the way... // if (dataSmoothed != null) // chartPValues.getData().setAll(new XYChart.Series<>("P-values", data), new XYChart.Series<>("Smoothed P-values", dataSmoothed)); // else chartPValues.getData().setAll(new XYChart.Series<>("P-values", data)); // Add line to show 0.05 significance threshold if (pValueThresholds.length > 1) { Data<Number, Number> sigData1 = new Data<>(pValueThresholds[0], 0.05); Data<Number, Number> sigData2 = new Data<>(pValueThresholds[pValueThresholds.length - 1], 0.05); XYChart.Series<Number, Number> dataSignificant = new XYChart.Series<>("Signficance 0.05", FXCollections.observableArrayList(sigData1, sigData2)); chartPValues.getData().add(dataSignificant); sigData1.getNode().setVisible(false); sigData2.getNode().setVisible(false); } // chartPValues.getData().get(0).getNode().setVisible(true); // pValuesWrapper.clearThresholds(); for (XYChart.Data<Number, Number> dataPoint : data) { if (!Boolean.TRUE.equals(dataPoint.getExtraValue())) dataPoint.getNode().setVisible(false); } // if (dataSmoothed != null) { // for (XYChart.Data<Number, Number> dataPoint : dataSmoothed) { // dataPoint.getNode().setVisible(false); // } // chartPValues.getData().get(1).getNode().setOpacity(0.5); // } // int count = 0; // for (int i = 0; i < pValueThresholds.length; i++) { // double pValue = pValues[i]; // if (Double.isNaN(pValue)) // continue; // boolean observed = pValueThresholdsObserved[i]; //// if (observed) //// pValuesWrapper.addThreshold(new ReadOnlyDoubleWrapper(pValueThresholds[i]), Color.rgb(0, 0, 0, 0.05)); // // if (!observed) { //// StackPane pane = (StackPane)data.get(count).getNode(); //// pane.setEffect(new DropShadow()); // data.get(count).getNode().setVisible(false); // } // count++; // } } for (int i = 0; i < threshProperties.length; i++) { if (i < thresholds.length) threshProperties[i].set(thresholds[i]); else threshProperties[i].set(Double.NaN); } boolean isInteractive = interactiveThresholds(); histogramWrapper.setIsInteractive(isInteractive); pValuesWrapper.setIsInteractive(isInteractive); chartPValues.setVisible(true); } // else // chartPValues.setVisible(false); // Store values for next time scoreData = newScoreData; }
From source file:com.ggvaidya.scinames.dataset.DatasetSceneController.java
private void setupTableWithChanges(TableView<Change> tv, Dataset tp) { tv.setEditable(true);/*from ww w. j av a2 s . c o m*/ tv.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); tv.getColumns().clear(); TableColumn<Change, ChangeType> colChangeType = new TableColumn<>("Type"); colChangeType.setCellFactory(ComboBoxTableCell.forTableColumn(new ChangeTypeStringConverter(), ChangeType.ADDITION, ChangeType.DELETION, ChangeType.RENAME, ChangeType.LUMP, ChangeType.SPLIT, ChangeType.COMPLEX, ChangeType.ERROR)); colChangeType.setCellValueFactory(new PropertyValueFactory<>("type")); colChangeType.setPrefWidth(100.0); colChangeType.setEditable(true); tv.getColumns().add(colChangeType); TableColumn<Change, ObservableSet<Name>> colChangeFrom = new TableColumn<>("From"); colChangeFrom.setCellFactory(TextFieldTableCell.forTableColumn(new NameSetStringConverter())); colChangeFrom.setCellValueFactory(new PropertyValueFactory<>("from")); colChangeFrom.setPrefWidth(200.0); colChangeFrom.setEditable(true); tv.getColumns().add(colChangeFrom); TableColumn<Change, ObservableSet<Name>> colChangeTo = new TableColumn<>("To"); colChangeTo.setCellFactory(TextFieldTableCell.forTableColumn(new NameSetStringConverter())); colChangeTo.setCellValueFactory(new PropertyValueFactory<>("to")); colChangeTo.setPrefWidth(200.0); colChangeTo.setEditable(true); tv.getColumns().add(colChangeTo); TableColumn<Change, String> colExplicit = new TableColumn<>("Explicit or implicit?"); colExplicit.setCellValueFactory( (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper( features.getValue().getDataset().isChangeImplicit(features.getValue()) ? "Implicit" : "Explicit")); tv.getColumns().add(colExplicit); ChangeFilter cf = datasetView.getProjectView().getProject().getChangeFilter(); TableColumn<Change, String> colFiltered = new TableColumn<>("Eliminated by filter?"); colFiltered.setCellValueFactory( (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper( cf.test(features.getValue()) ? "Allowed" : "Eliminated")); tv.getColumns().add(colFiltered); TableColumn<Change, String> colNote = new TableColumn<>("Note"); colNote.setCellFactory(TextFieldTableCell.forTableColumn()); colNote.setCellValueFactory(new PropertyValueFactory<>("note")); colNote.setPrefWidth(100.0); colNote.setEditable(true); tv.getColumns().add(colNote); TableColumn<Change, String> colCitations = new TableColumn<>("Citations"); colCitations.setCellValueFactory( (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper( features.getValue().getCitationStream().map(citation -> citation.getCitation()).sorted() .collect(Collectors.joining("; ")))); tv.getColumns().add(colCitations); TableColumn<Change, String> colGenera = new TableColumn<>("Genera"); colGenera.setCellValueFactory( (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper( String.join(", ", features.getValue().getAllNames().stream().map(n -> n.getGenus()) .distinct().sorted().collect(Collectors.toList())))); tv.getColumns().add(colGenera); TableColumn<Change, String> colSpecificEpithet = new TableColumn<>("Specific epithets"); colSpecificEpithet.setCellValueFactory( (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(String .join(", ", features.getValue().getAllNames().stream().map(n -> n.getSpecificEpithet()) .filter(s -> s != null).distinct().sorted().collect(Collectors.toList())))); tv.getColumns().add(colSpecificEpithet); // The infraspecific string. TableColumn<Change, String> colInfraspecificEpithet = new TableColumn<>("Infraspecific epithets"); colInfraspecificEpithet.setCellValueFactory( (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper( String.join(", ", features.getValue().getAllNames().stream() .map(n -> n.getInfraspecificEpithetsAsString()).filter(s -> s != null) .distinct().sorted().collect(Collectors.toList())))); tv.getColumns().add(colInfraspecificEpithet); // The very last epithet of all TableColumn<Change, String> colTerminalEpithet = new TableColumn<>("Terminal epithet"); colTerminalEpithet.setCellValueFactory( (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper( String.join(", ", features.getValue().getAllNames().stream().map(n -> { List<Name.InfraspecificEpithet> infraspecificEpithets = n.getInfraspecificEpithets(); if (!infraspecificEpithets.isEmpty()) { return infraspecificEpithets.get(infraspecificEpithets.size() - 1).getValue(); } else { return n.getSpecificEpithet(); } }).filter(s -> s != null).distinct().sorted().collect(Collectors.toList())))); tv.getColumns().add(colTerminalEpithet); // Properties TableColumn<Change, String> colProperties = new TableColumn<>("Properties"); colProperties.setCellValueFactory( (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper( features.getValue().getProperties().entrySet().stream() .map(entry -> entry.getKey() + ": " + entry.getValue()).sorted() .collect(Collectors.joining("; ")))); tv.getColumns().add(colProperties); fillTableWithChanges(tv, tp); // When someone selects a cell in the Table, try to select the appropriate data in the // additional data view. tv.getSelectionModel().getSelectedItems().addListener((ListChangeListener<Change>) lcl -> { AdditionalData aData = additionalDataCombobox.getSelectionModel().getSelectedItem(); if (aData != null) { aData.onSelectChange(tv.getSelectionModel().getSelectedItems()); } }); // Create a right-click menu for table rows. changesTableView.setRowFactory(table -> { TableRow<Change> row = new TableRow<>(); row.setOnContextMenuRequested(event -> { if (row.isEmpty()) return; // We don't currently use the clicked change, since currently all options // change *all* the selected changes, but this may change in the future. Change change = row.getItem(); ContextMenu changeMenu = new ContextMenu(); Menu searchForName = new Menu("Search for name"); searchForName.getItems().addAll( change.getAllNames().stream().sorted().map(n -> createMenuItem(n.getFullName(), action -> { datasetView.getProjectView().openDetailedView(n); })).collect(Collectors.toList())); changeMenu.getItems().add(searchForName); changeMenu.getItems().add(new SeparatorMenuItem()); changeMenu.getItems().add(createMenuItem("Edit note", action -> { List<Change> changes = new ArrayList<>(changesTableView.getSelectionModel().getSelectedItems()); String combinedNotes = changes.stream().map(ch -> ch.getNote().orElse("").trim()).distinct() .collect(Collectors.joining("\n")).trim(); Optional<String> result = askUserForTextArea( "Modify the note for these " + changes.size() + " changes:", combinedNotes); if (result.isPresent()) { String note = result.get().trim(); LOGGER.info("Using 'Edit note' to set note to '" + note + "' on changes " + changes); changes.forEach(ch -> ch.noteProperty().set(note)); } })); changeMenu.getItems().add(new SeparatorMenuItem()); // Create a submenu for tags and urls. String note = change.noteProperty().get(); Menu removeTags = new Menu("Tags"); removeTags.getItems().addAll(change.getTags().stream().sorted() .map(tag -> new MenuItem(tag.getName())).collect(Collectors.toList())); Menu lookupURLs = new Menu("Lookup URL"); change.getURIs().stream().sorted().map(uri -> { return createMenuItem(uri.toString(), evt -> { try { Desktop.getDesktop().browse(uri); } catch (IOException ex) { LOGGER.warning("Could not open URL '" + uri + "': " + ex); } }); }).forEach(mi -> lookupURLs.getItems().add(mi)); changeMenu.getItems().add(lookupURLs); changeMenu.getItems().add(new SeparatorMenuItem()); changeMenu.getItems().add(createMenuItem("Prepend text to all notes", action -> { List<Change> changes = new ArrayList<>(changesTableView.getSelectionModel().getSelectedItems()); Optional<String> result = askUserForTextField( "Enter tags to prepend to notes in " + changes.size() + " changes:"); if (result.isPresent()) { String tags = result.get().trim(); changes.forEach(ch -> { String prevValue = change.getNote().orElse("").trim(); LOGGER.info("Prepending tags '" + tags + "' to previous value '" + prevValue + "' for change " + ch); ch.noteProperty().set((tags + " " + prevValue).trim()); }); } })); changeMenu.getItems().add(createMenuItem("Append text to all notes", action -> { List<Change> changes = new ArrayList<>(changesTableView.getSelectionModel().getSelectedItems()); Optional<String> result = askUserForTextField( "Enter tags to append to notes in " + changes.size() + " changes:"); if (result.isPresent()) { String tags = result.get().trim(); changes.forEach(ch -> { String prevValue = ch.getNote().orElse("").trim(); LOGGER.info("Appending tags '" + tags + "' to previous value '" + prevValue + "' for change " + ch); ch.noteProperty().setValue((prevValue + " " + tags).trim()); }); } })); changeMenu.show(datasetView.getScene().getWindow(), event.getScreenX(), event.getScreenY()); }); return row; }); LOGGER.info("setupTableWithChanges() completed"); }
From source file:snpviewer.SnpViewer.java
private void drawSavedRegions(String chrom) { selectionOverlayPane.getChildren().clear(); if (savedRegions.isEmpty()) { selectionOverlayPane.getChildren().add(dragSelectRectangle); return;//from w w w . ja va 2 s .c o m } for (RegionSummary r : savedRegions) { if (r.getChromosome() == null) { selectionOverlayPane.getChildren().add(dragSelectRectangle); return; } if (r.getChromosome().equalsIgnoreCase(chrom)) { drawRegionSummary(r, chrom); } } int rectCounter = 0; for (final Rectangle rect : savedRegionsDisplay) { final int counter = rectCounter; final ContextMenu scm = new ContextMenu(); final MenuItem scmItem1 = new MenuItem("Display Flanking SNP IDs"); scmItem1.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { /* get coordinates of selection and report back * flanking snp ids and coordinates */ displayFlankingSnpIDs(rect); } }); final MenuItem scmItem2 = new MenuItem("Write Region to File"); scmItem2.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { Platform.runLater(new Runnable() { @Override public void run() { /* get coordinates of selection and * write SNPs in region to file */ writeRegionToFile(rect); } }); } }); final MenuItem scmItem3 = new MenuItem("Remove this Saved Region"); scmItem3.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { /* get coordinates of selection and * write SNPs in region to file */ removeSavedRegion(counter); } }); final MenuItem scmItem4 = new MenuItem("Show/Hide Saved Regions"); scmItem4.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { /* get coordinates of selection and report back * write SNPs in region to file */ hideSavedRegionsMenu.selectedProperty().setValue(!hideSavedRegionsMenu.isSelected()); hideSavedRegionsMenu.fire(); } }); final MenuItem scmItem5 = new MenuItem("Zoom Region"); scmItem5.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { /* get coordinates of selection and report back * write SNPs in region to file */ zoomRegion(rect); } }); final MenuItem scmItem6 = new MenuItem("Write Saved Regions to File"); scmItem6.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { Platform.runLater(new Runnable() { @Override public void run() { /* get coordinates of selection and report back * write SNPs in region to file */ writeSavedRegionsToFile(); } }); } }); scm.getItems().add(scmItem1); scm.getItems().add(scmItem2); scm.getItems().add(scmItem3); scm.getItems().add(scmItem4); scm.getItems().add(scmItem5); scm.getItems().add(scmItem6); rect.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent e) { ocm.hide(); if (scm.isShowing()) { scm.hide(); } if (e.getButton() == MouseButton.SECONDARY) { if (chromosomeSelector.getSelectionModel().isEmpty()) { for (MenuItem mi : scm.getItems()) { mi.setDisable(true); } } else { for (MenuItem mi : scm.getItems()) { mi.setDisable(false); } } scm.show(selectionOverlayPane, e.getScreenX(), e.getScreenY()); } } }); rect.setVisible(true); selectionOverlayPane.getChildren().add(rect); rectCounter++; } selectionOverlayPane.getChildren().add(dragSelectRectangle); }
From source file:fr.amap.lidar.amapvox.gui.MainFrameController.java
/** * Initializes the controller class./*from w w w .j a v a 2s . com*/ */ @Override public void initialize(URL url, ResourceBundle rb) { this.resourceBundle = rb; viewer3DPanelController.setResourceBundle(rb); initStrings(rb); colorPickerSeries.valueProperty().addListener(new ChangeListener<javafx.scene.paint.Color>() { @Override public void changed(ObservableValue<? extends javafx.scene.paint.Color> observable, javafx.scene.paint.Color oldValue, javafx.scene.paint.Color newValue) { if (listViewVoxelsFilesChart.getSelectionModel().getSelectedItems().size() == 1) { listViewVoxelsFilesChart.getSelectionModel().getSelectedItem().getSeriesParameters() .setColor(new Color((float) newValue.getRed(), (float) newValue.getGreen(), (float) newValue.getBlue(), 1.0f)); } } }); comboboxScript.getItems().setAll("Daniel script"); vboxWeighting.disableProperty().bind(checkboxEnableWeighting.selectedProperty().not()); checkboxEnableWeighting.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue && textAreaWeighting.getText().isEmpty()) { int selectedVoxTab = tabPaneVoxelisation.getSelectionModel().getSelectedIndex(); if (selectedVoxTab == 0) { //ALS fillWeightingData(EchoesWeightParams.DEFAULT_ALS_WEIGHTING); } else if (selectedVoxTab == 1) { //TLS fillWeightingData(EchoesWeightParams.DEFAULT_TLS_WEIGHTING); } } } }); /*comboboxTransMode.getItems().setAll(1, 2, 3); comboboxTransMode.getSelectionModel().selectFirst(); comboboxPathLengthMode.getItems().setAll("A", "B"); comboboxPathLengthMode.getSelectionModel().selectFirst();*/ helpButtonNaNsCorrection.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { helpButtonNaNsCorrectionController.showHelpDialog(resourceBundle.getString("help_NaNs_correction")); } }); helpButtonAutoBBox.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { helpButtonAutoBBoxController.showHelpDialog(resourceBundle.getString("help_bbox")); } }); helpButtonHemiPhoto.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { helpButtonHemiPhotoController.showHelpDialog(resourceBundle.getString("help_hemiphoto")); } }); buttonHelpEmptyShotsFilter.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { buttonHelpEmptyShotsFilterController .showHelpDialog(resourceBundle.getString("help_empty_shots_filter")); } }); /*work around, the divider positions values are defined in the fxml, but when the window is initialized the values are lost*/ Platform.runLater(new Runnable() { @Override public void run() { splitPaneMain.setDividerPositions(0.75f); splitPaneVoxelization.setDividerPositions(0.45f); } }); initValidationSupport(); initPostProcessTab(); listViewTransmittanceMapSensorPositions.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); listViewTaskList.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); MenuItem menuItemPadValue1m = new MenuItem("1m voxel size"); addMenuItemPadValue(menuItemPadValue1m, 3.536958f); MenuItem menuItemPadValue2m = new MenuItem("2m voxel size"); addMenuItemPadValue(menuItemPadValue2m, 2.262798f); MenuItem menuItemPadValue3m = new MenuItem("3m voxel size"); addMenuItemPadValue(menuItemPadValue3m, 1.749859f); MenuItem menuItemPadValue4m = new MenuItem("4m voxel size"); addMenuItemPadValue(menuItemPadValue4m, 1.3882959f); MenuItem menuItemPadValue5m = new MenuItem("5m voxel size"); addMenuItemPadValue(menuItemPadValue5m, 1.0848f); menuButtonAdvisablePADMaxValues.getItems().addAll(menuItemPadValue1m, menuItemPadValue2m, menuItemPadValue3m, menuItemPadValue4m, menuItemPadValue5m); fileChooserSaveCanopyAnalyserOutputFile = new FileChooserContext(); fileChooserSaveCanopyAnalyserCfgFile = new FileChooserContext(); fileChooserSaveTransmittanceSimCfgFile = new FileChooserContext(); fileChooserOpenCanopyAnalyserInputFile = new FileChooserContext(); listViewCanopyAnalyzerSensorPositions.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); ContextMenu contextMenuProductsList = new ContextMenu(); MenuItem openImageItem = new MenuItem(RS_STR_OPEN_IMAGE); openImageItem.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { File selectedFile = listViewProductsFiles.getSelectionModel().getSelectedItem(); showImage(selectedFile); } }); Menu menuEdit = new Menu(RS_STR_EDIT); MenuItem menuItemEditVoxels = new MenuItem("Remove voxels (delete key)"); MenuItem menuItemFitToContent = new MenuItem("Fit to content"); MenuItem menuItemCrop = new MenuItem("Crop"); menuEdit.getItems().setAll(menuItemEditVoxels, menuItemFitToContent, menuItemCrop); menuItemFitToContent.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { File selectedItem = listViewProductsFiles.getSelectionModel().getSelectedItem(); if (selectedItem != null) { fitVoxelSpaceToContent(selectedItem); } } }); menuItemEditVoxels.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { File selectedItem = listViewProductsFiles.getSelectionModel().getSelectedItem(); if (selectedItem != null) { editVoxelSpace(selectedItem); } } }); menuItemCrop.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { File selectedItem = listViewProductsFiles.getSelectionModel().getSelectedItem(); if (selectedItem != null) { try { voxelSpaceCroppingFrameController.setVoxelFile(selectedItem); voxelSpaceCroppingFrame.show(); } catch (Exception ex) { showErrorDialog(ex); } } } }); Menu menuExport = new Menu(RS_STR_EXPORT); MenuItem menuItemExportDartMaket = new MenuItem("Dart (maket.txt)"); MenuItem menuItemExportDartPlots = new MenuItem("Dart (plots.xml)"); MenuItem menuItemExportMeshObj = new MenuItem("Mesh (*.obj)"); menuItemExportDartMaket.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { File selectedItem = listViewProductsFiles.getSelectionModel().getSelectedItem(); if (selectedItem != null) { exportDartMaket(selectedItem); } } }); menuItemExportDartPlots.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { File selectedItem = listViewProductsFiles.getSelectionModel().getSelectedItem(); if (selectedItem != null) { exportDartPlots(selectedItem); } } }); menuItemExportMeshObj.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { File selectedItem = listViewProductsFiles.getSelectionModel().getSelectedItem(); if (selectedItem != null) { exportMeshObj(selectedItem); } } }); menuExport.getItems().setAll(menuItemExportDartMaket, menuItemExportDartPlots, menuItemExportMeshObj); MenuItem menuItemInfo = new MenuItem(RS_STR_INFO); menuItemInfo.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { Alert alert = new Alert(AlertType.INFORMATION); File selectedItem = listViewProductsFiles.getSelectionModel().getSelectedItem(); if (selectedItem != null) { VoxelFileReader reader; try { reader = new VoxelFileReader(selectedItem); VoxelSpaceInfos voxelSpaceInfos = reader.getVoxelSpaceInfos(); alert.setTitle("Information"); alert.setHeaderText("Voxel space informations"); alert.setContentText(voxelSpaceInfos.toString()); alert.show(); } catch (Exception ex) { showErrorDialog(ex); } } } }); final MenuItem menuItemOpenContainingFolder = new MenuItem(RS_STR_OPEN_CONTAINING_FOLDER); menuItemOpenContainingFolder.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { final File selectedItem = listViewProductsFiles.getSelectionModel().getSelectedItem(); if (selectedItem != null) { if (Desktop.isDesktopSupported()) { new Thread(() -> { try { Desktop.getDesktop().open(selectedItem.getParentFile()); } catch (IOException ex) { logger.error("Cannot open directory " + selectedItem); } }).start(); } } } }); listViewProductsFiles.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() { @Override public void handle(ContextMenuEvent event) { if (listViewProductsFiles.getSelectionModel().getSelectedIndices().size() == 1) { File selectedFile = listViewProductsFiles.getSelectionModel().getSelectedItem(); String extension = FileManager.getExtension(selectedFile); switch (extension) { case ".png": case ".bmp": case ".jpg": contextMenuProductsList.getItems().setAll(openImageItem, menuItemOpenContainingFolder); contextMenuProductsList.show(listViewProductsFiles, event.getScreenX(), event.getScreenY()); break; case ".vox": default: if (VoxelFileReader.isFileAVoxelFile(selectedFile)) { contextMenuProductsList.getItems().setAll(menuItemInfo, menuItemOpenContainingFolder, menuEdit, menuExport); contextMenuProductsList.show(listViewProductsFiles, event.getScreenX(), event.getScreenY()); } } } } }); ContextMenu contextMenuLidarScanEdit = new ContextMenu(); MenuItem editItem = new MenuItem("Edit"); editItem.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { filterFrameController.setFilters("Reflectance", "Deviation", "Amplitude"); filterFrame.show(); filterFrame.setOnHidden(new EventHandler<WindowEvent>() { @Override public void handle(WindowEvent event) { if (filterFrameController.getFilter() != null) { ObservableList<LidarScan> items = listViewHemiPhotoScans.getSelectionModel() .getSelectedItems(); for (LidarScan scan : items) { scan.filters.add(filterFrameController.getFilter()); } } } }); } }); contextMenuLidarScanEdit.getItems().add(editItem); listViewHemiPhotoScans.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); listViewHemiPhotoScans.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() { @Override public void handle(ContextMenuEvent event) { contextMenuLidarScanEdit.show(listViewHemiPhotoScans, event.getScreenX(), event.getScreenY()); } }); /**LAD tab initialization**/ comboboxLADChoice.getItems().addAll(LeafAngleDistribution.Type.UNIFORM, LeafAngleDistribution.Type.SPHERIC, LeafAngleDistribution.Type.ERECTOPHILE, LeafAngleDistribution.Type.PLANOPHILE, LeafAngleDistribution.Type.EXTREMOPHILE, LeafAngleDistribution.Type.PLAGIOPHILE, LeafAngleDistribution.Type.HORIZONTAL, LeafAngleDistribution.Type.VERTICAL, LeafAngleDistribution.Type.ELLIPSOIDAL, LeafAngleDistribution.Type.ELLIPTICAL, LeafAngleDistribution.Type.TWO_PARAMETER_BETA); comboboxLADChoice.getSelectionModel().select(LeafAngleDistribution.Type.SPHERIC); comboboxLADChoice.getSelectionModel().selectedItemProperty() .addListener(new ChangeListener<LeafAngleDistribution.Type>() { @Override public void changed(ObservableValue<? extends LeafAngleDistribution.Type> observable, LeafAngleDistribution.Type oldValue, LeafAngleDistribution.Type newValue) { if (newValue == LeafAngleDistribution.Type.TWO_PARAMETER_BETA || newValue == LeafAngleDistribution.Type.ELLIPSOIDAL) { hboxTwoBetaParameters.setVisible(true); if (newValue == LeafAngleDistribution.Type.ELLIPSOIDAL) { labelLADBeta.setVisible(false); } else { labelLADBeta.setVisible(true); } } else { hboxTwoBetaParameters.setVisible(false); } } }); ToggleGroup ladTypeGroup = new ToggleGroup(); radiobuttonLADHomogeneous.setToggleGroup(ladTypeGroup); radiobuttonLADLocalEstimation.setToggleGroup(ladTypeGroup); /**CHART panel initialization**/ ToggleGroup profileChartType = new ToggleGroup(); radiobuttonPreDefinedProfile.setToggleGroup(profileChartType); radiobuttonFromVariableProfile.setToggleGroup(profileChartType); ToggleGroup profileChartRelativeHeightType = new ToggleGroup(); radiobuttonHeightFromAboveGround.setToggleGroup(profileChartRelativeHeightType); radiobuttonHeightFromBelowCanopy.setToggleGroup(profileChartRelativeHeightType); comboboxFromVariableProfile.disableProperty().bind(radiobuttonPreDefinedProfile.selectedProperty()); comboboxPreDefinedProfile.disableProperty().bind(radiobuttonFromVariableProfile.selectedProperty()); hboxMaxPADVegetationProfile.visibleProperty().bind(radiobuttonPreDefinedProfile.selectedProperty()); listViewVoxelsFilesChart.getSelectionModel().selectedIndexProperty() .addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { if (listViewVoxelsFilesChart.getSelectionModel().getSelectedItems().size() > 1) { colorPickerSeries.setDisable(true); } else if (listViewVoxelsFilesChart.getSelectionModel().getSelectedItems().size() == 1) { VoxelFileChart selectedItem = listViewVoxelsFilesChart.getSelectionModel() .getSelectedItem(); Color selectedItemColor = selectedItem.getSeriesParameters().getColor(); colorPickerSeries.setDisable(false); colorPickerSeries.setValue(new javafx.scene.paint.Color( selectedItemColor.getRed() / 255.0, selectedItemColor.getGreen() / 255.0, selectedItemColor.getBlue() / 255.0, 1.0)); if (newValue.intValue() >= 0) { textfieldLabelVoxelFileChart.setText( listViewVoxelsFilesChart.getItems().get(newValue.intValue()).label); } } } }); textfieldLabelVoxelFileChart.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (listViewVoxelsFilesChart.getSelectionModel().getSelectedIndex() >= 0) { listViewVoxelsFilesChart.getSelectionModel().getSelectedItem().label = newValue; } } }); listViewVoxelsFilesChart.getItems().addListener(new ListChangeListener<VoxelFileChart>() { @Override public void onChanged(ListChangeListener.Change<? extends VoxelFileChart> c) { while (c.next()) { } if (c.wasAdded() && c.getAddedSize() == c.getList().size()) { try { VoxelFileReader reader = new VoxelFileReader(c.getList().get(0).file); String[] columnNames = reader.getVoxelSpaceInfos().getColumnNames(); comboboxFromVariableProfile.getItems().clear(); comboboxFromVariableProfile.getItems().addAll(columnNames); comboboxFromVariableProfile.getSelectionModel().selectFirst(); } catch (Exception ex) { logger.error("Cannot read voxel file", ex); } } } }); anchorpaneQuadrats.disableProperty().bind(checkboxMakeQuadrats.selectedProperty().not()); comboboxSelectAxisForQuadrats.getItems().addAll("X", "Y", "Z"); comboboxSelectAxisForQuadrats.getSelectionModel().select(1); comboboxPreDefinedProfile.getItems().addAll("Vegetation (PAD)"); comboboxPreDefinedProfile.getSelectionModel().selectFirst(); radiobuttonSplitCountForQuadrats.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { textFieldSplitCountForQuadrats.setDisable(!newValue); textFieldLengthForQuadrats.setDisable(newValue); } }); ToggleGroup chartMakeQuadratsSplitType = new ToggleGroup(); radiobuttonLengthForQuadrats.setToggleGroup(chartMakeQuadratsSplitType); radiobuttonSplitCountForQuadrats.setToggleGroup(chartMakeQuadratsSplitType); /**Virtual measures panel initialization**/ comboboxHemiPhotoBitmapOutputMode.getItems().addAll("Pixel", "Color"); comboboxHemiPhotoBitmapOutputMode.getSelectionModel().selectFirst(); ToggleGroup virtualMeasuresChoiceGroup = new ToggleGroup(); toggleButtonLAI2000Choice.setToggleGroup(virtualMeasuresChoiceGroup); toggleButtonLAI2200Choice.setToggleGroup(virtualMeasuresChoiceGroup); comboboxChooseCanopyAnalyzerSampling.getItems().setAll(500, 4000, 10000); comboboxChooseCanopyAnalyzerSampling.getSelectionModel().selectFirst(); initEchoFiltering(); data = FXCollections.observableArrayList(); tableViewSimulationPeriods.setItems(data); tableViewSimulationPeriods.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); comboboxChooseDirectionsNumber.getItems().addAll(1, 6, 16, 46, 136, 406); comboboxChooseDirectionsNumber.getSelectionModel().select(4); ToggleGroup scannerPositionsMode = new ToggleGroup(); /*radiobuttonScannerPosSquaredArea.setToggleGroup(scannerPositionsMode); radiobuttonScannerPosFile.setToggleGroup(scannerPositionsMode);*/ tableColumnPeriod.setCellValueFactory( new Callback<TableColumn.CellDataFeatures<SimulationPeriod, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call( TableColumn.CellDataFeatures<SimulationPeriod, String> param) { return new SimpleStringProperty(param.getValue().getPeriod().toString()); } }); tableColumnClearness.setCellValueFactory( new Callback<TableColumn.CellDataFeatures<SimulationPeriod, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call( TableColumn.CellDataFeatures<SimulationPeriod, String> param) { return new SimpleStringProperty(String.valueOf(param.getValue().getClearnessCoefficient())); } }); checkboxMultiFiles.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { anchorpaneBoundingBoxParameters.setDisable(newValue); } }); hboxGenerateBitmapFiles.disableProperty().bind(checkboxGenerateBitmapFile.selectedProperty().not()); hboxGenerateTextFile.disableProperty().bind(checkboxGenerateTextFile.selectedProperty().not()); fileChooserOpenConfiguration = new FileChooser(); fileChooserOpenConfiguration.setTitle("Choose configuration file"); fileChooserSaveConfiguration = new FileChooserContext("cfg.xml"); fileChooserSaveConfiguration.fc.setTitle("Choose output file"); fileChooserOpenInputFileALS = new FileChooser(); fileChooserOpenInputFileALS.setTitle("Open input file"); fileChooserOpenInputFileALS.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"), new ExtensionFilter("Shot files", "*.sht"), new ExtensionFilter("Text Files", "*.txt"), new ExtensionFilter("Las Files", "*.las", "*.laz")); fileChooserOpenTrajectoryFileALS = new FileChooser(); fileChooserOpenTrajectoryFileALS.setTitle("Open trajectory file"); fileChooserOpenTrajectoryFileALS.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"), new ExtensionFilter("Text Files", "*.txt")); fileChooserOpenOutputFileALS = new FileChooser(); fileChooserOpenOutputFileALS.setTitle("Choose output file"); fileChooserOpenInputFileTLS = new FileChooserContext(); fileChooserOpenInputFileTLS.fc.setTitle("Open input file"); fileChooserOpenInputFileTLS.fc.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"), new ExtensionFilter("Text Files", "*.txt"), new ExtensionFilter("Rxp Files", "*.rxp"), new ExtensionFilter("Project Rsp Files", "*.rsp")); directoryChooserOpenOutputPathTLS = new DirectoryChooser(); directoryChooserOpenOutputPathTLS.setTitle("Choose output path"); directoryChooserOpenOutputPathALS = new DirectoryChooser(); directoryChooserOpenOutputPathALS.setTitle("Choose output path"); fileChooserSaveOutputFileTLS = new FileChooser(); fileChooserSaveOutputFileTLS.setTitle("Save voxel file"); fileChooserSaveTransmittanceTextFile = new FileChooser(); fileChooserSaveTransmittanceTextFile.setTitle("Save text file"); directoryChooserSaveTransmittanceBitmapFile = new DirectoryChooser(); directoryChooserSaveTransmittanceBitmapFile.setTitle("Choose output directory"); fileChooserSaveHemiPhotoOutputBitmapFile = new FileChooserContext("*.png"); fileChooserSaveHemiPhotoOutputBitmapFile.fc.setTitle("Save bitmap file"); directoryChooserSaveHemiPhotoOutputBitmapFile = new DirectoryChooser(); directoryChooserSaveHemiPhotoOutputBitmapFile.setTitle("Choose bitmap files output directory"); directoryChooserSaveHemiPhotoOutputTextFile = new DirectoryChooser(); directoryChooserSaveHemiPhotoOutputTextFile.setTitle("Choose text files output directory"); fileChooserSaveHemiPhotoOutputTextFile = new FileChooser(); fileChooserSaveHemiPhotoOutputTextFile.setTitle("Save text file"); fileChooserOpenVoxelFile = new FileChooser(); fileChooserOpenVoxelFile.setTitle("Open voxel file"); fileChooserOpenVoxelFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"), new ExtensionFilter("Voxel Files", "*.vox")); fileChooserOpenPopMatrixFile = new FileChooser(); fileChooserOpenPopMatrixFile.setTitle("Choose matrix file"); fileChooserOpenPopMatrixFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"), new ExtensionFilter("Text Files", "*.txt")); fileChooserOpenSopMatrixFile = new FileChooser(); fileChooserOpenSopMatrixFile.setTitle("Choose matrix file"); fileChooserOpenSopMatrixFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"), new ExtensionFilter("Text Files", "*.txt")); fileChooserOpenVopMatrixFile = new FileChooser(); fileChooserOpenVopMatrixFile.setTitle("Choose matrix file"); fileChooserOpenVopMatrixFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"), new ExtensionFilter("Text Files", "*.txt")); fileChooserOpenPonderationFile = new FileChooser(); fileChooserOpenPonderationFile.setTitle("Choose ponderation file"); fileChooserOpenPonderationFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"), new ExtensionFilter("Text Files", "*.txt")); fileChooserOpenDTMFile = new FileChooser(); fileChooserOpenDTMFile.setTitle("Choose DTM file"); fileChooserOpenDTMFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"), new ExtensionFilter("DTM Files", "*.asc")); fileChooserOpenPointCloudFile = new FileChooser(); fileChooserOpenPointCloudFile.setTitle("Choose point cloud file"); fileChooserOpenPointCloudFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"), new ExtensionFilter("TXT Files", "*.txt")); fileChooserOpenMultiResVoxelFile = new FileChooser(); fileChooserOpenMultiResVoxelFile.setTitle("Choose voxel file"); fileChooserOpenMultiResVoxelFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"), new ExtensionFilter("Voxel Files", "*.vox")); fileChooserOpenOutputFileMultiRes = new FileChooser(); fileChooserOpenOutputFileMultiRes.setTitle("Save voxel file"); fileChooserAddTask = new FileChooser(); fileChooserAddTask.setTitle("Choose parameter file"); fileChooserAddTask.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"), new ExtensionFilter("XML Files", "*.xml")); fileChooserSaveDartFile = new FileChooser(); fileChooserSaveDartFile.setTitle("Save dart file (.maket)"); fileChooserSaveDartFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"), new ExtensionFilter("Maket File", "*.maket")); fileChooserOpenOutputFileMerging = new FileChooser(); fileChooserOpenOutputFileMerging.setTitle("Choose voxel file"); fileChooserOpenOutputFileMerging.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"), new ExtensionFilter("Voxel Files", "*.vox")); fileChooserOpenScriptFile = new FileChooser(); fileChooserOpenScriptFile.setTitle("Choose script file"); fileChooserSaveGroundEnergyOutputFile = new FileChooser(); fileChooserSaveGroundEnergyOutputFile.setTitle("Save ground energy file"); fileChooserOpenPointsPositionFile = new FileChooser(); fileChooserOpenPointsPositionFile.setTitle("Choose points file"); fileChooserOpenPointsPositionFile.getExtensionFilters().addAll(new ExtensionFilter("All Files", "*"), new ExtensionFilter("TXT Files", "*.txt")); try { viewCapsSetupFrame = new Stage(); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/ViewCapsSetupFrame.fxml")); Parent root = loader.load(); viewCapsSetupFrameController = loader.getController(); viewCapsSetupFrame.setScene(new Scene(root)); } catch (IOException ex) { logger.error("Cannot load fxml file", ex); } try { FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/FilteringPaneComponent.fxml")); anchorPaneEchoFilteringRxp = loader.load(); filteringPaneController = loader.getController(); filteringPaneController.setFiltersNames("Reflectance", "Amplitude", "Deviation"); } catch (IOException ex) { logger.error("Cannot load fxml file", ex); } try { positionImporterFrame = new Stage(); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/PositionImporterFrame.fxml")); Parent root = loader.load(); positionImporterFrameController = loader.getController(); positionImporterFrame.setScene(new Scene(root)); positionImporterFrameController.setStage(positionImporterFrame); } catch (IOException ex) { logger.error("Cannot load fxml file", ex); } try { voxelSpaceCroppingFrame = new Stage(); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/VoxelSpaceCroppingFrame.fxml")); Parent root = loader.load(); voxelSpaceCroppingFrameController = loader.getController(); voxelSpaceCroppingFrame.setScene(new Scene(root)); } catch (IOException ex) { logger.error("Cannot load fxml file", ex); } try { attributsImporterFrame = new Stage(); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/AttributsImporterFrame.fxml")); Parent root = loader.load(); attributsImporterFrameController = loader.getController(); attributsImporterFrame.setScene(new Scene(root)); attributsImporterFrameController.setStage(attributsImporterFrame); } catch (IOException ex) { logger.error("Cannot load fxml file", ex); } try { textFileParserFrameController = TextFileParserFrameController.getInstance(); } catch (Exception ex) { logger.error("Cannot load fxml file", ex); } try { transformationFrameController = TransformationFrameController.getInstance(); transformationFrame = transformationFrameController.getStage(); } catch (Exception ex) { logger.error("Cannot load fxml file", ex); } updaterFrame = new Stage(); try { FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/update/UpdaterFrame.fxml")); Parent root = loader.load(); updaterFrameController = loader.getController(); updaterFrame.setScene(new Scene(root)); } catch (IOException ex) { logger.error("Cannot load fxml file", ex); } riscanProjectExtractor = new RiscanProjectExtractor(); ptxProjectExtractor = new PTXProjectExtractor(); ptgProjectExtractor = new PTGProjectExtractor(); dateChooserFrame = new Stage(); try { FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/DateChooserFrame.fxml")); Parent root = loader.load(); dateChooserFrameController = loader.getController(); dateChooserFrame.setScene(new Scene(root)); dateChooserFrameController.setStage(dateChooserFrame); } catch (IOException ex) { logger.error("Cannot load fxml file", ex); } comboboxModeALS.getItems().addAll(RS_STR_INPUT_TYPE_LAS, RS_STR_INPUT_TYPE_LAZ, /*RS_STR_INPUT_TYPE_XYZ, */RS_STR_INPUT_TYPE_SHOTS); comboboxModeALS.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (newValue.equals(RS_STR_INPUT_TYPE_SHOTS)) { alsVoxValidationSupport.registerValidator(textFieldTrajectoryFileALS, false, Validators.unregisterValidator); } else { alsVoxValidationSupport.registerValidator(textFieldTrajectoryFileALS, false, Validators.fileExistValidator); } } }); comboboxModeTLS.getItems().setAll("Rxp scan", "Rsp project", "PTX", "PTG"/*, RS_STR_INPUT_TYPE_XYZ, RS_STR_INPUT_TYPE_SHOTS*/); comboboxGroundEnergyOutputFormat.getItems().setAll("txt", "png"); comboboxLaserSpecification.getItems().addAll(LaserSpecification.getPresets()); comboboxLaserSpecification.getSelectionModel().selectedItemProperty() .addListener(new ChangeListener<LaserSpecification>() { @Override public void changed(ObservableValue<? extends LaserSpecification> observable, LaserSpecification oldValue, LaserSpecification newValue) { DecimalFormatSymbols symb = new DecimalFormatSymbols(); symb.setDecimalSeparator('.'); DecimalFormat formatter = new DecimalFormat("#####.######", symb); textFieldBeamDiameterAtExit.setText(formatter.format(newValue.getBeamDiameterAtExit())); textFieldBeamDivergence.setText(formatter.format(newValue.getBeamDivergence())); } }); comboboxLaserSpecification.getSelectionModel().select(LaserSpecification.LMS_Q560); comboboxLaserSpecification.disableProperty().bind(checkboxCustomLaserSpecification.selectedProperty()); textFieldBeamDiameterAtExit.disableProperty() .bind(checkboxCustomLaserSpecification.selectedProperty().not()); textFieldBeamDivergence.disableProperty().bind(checkboxCustomLaserSpecification.selectedProperty().not()); listViewProductsFiles.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); listViewProductsFiles.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { int size = listViewProductsFiles.getSelectionModel().getSelectedIndices().size(); if (size == 1) { viewer3DPanelController .updateCurrentVoxelFile(listViewProductsFiles.getSelectionModel().getSelectedItem()); } } }); listViewTaskList.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { int size = listViewTaskList.getSelectionModel().getSelectedIndices().size(); if (size == 1) { buttonLoadSelectedTask.setDisable(false); } else { buttonLoadSelectedTask.setDisable(true); } buttonExecute.setDisable(size == 0); } }); resetMatrices(); calculateMatrixFrame = new Stage(); try { FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/CalculateMatrixFrame.fxml")); Parent root = loader.load(); calculateMatrixFrameController = loader.getController(); calculateMatrixFrameController.setStage(calculateMatrixFrame); Scene scene = new Scene(root); calculateMatrixFrame.setScene(scene); } catch (IOException ex) { logger.error("Cannot load fxml file", ex); } filterFrame = new Stage(); try { FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/FilterFrame.fxml")); Parent root = loader.load(); filterFrameController = loader.getController(); filterFrameController.setStage(filterFrame); filterFrameController.setFilters("Angle"); filterFrame.setScene(new Scene(root)); } catch (IOException ex) { logger.error("Cannot load fxml file", ex); } try { FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/export/ObjExporterDialog.fxml")); Parent root = loader.load(); objExporterController = loader.getController(); Stage s = new Stage(); objExporterController.setStage(s); s.setScene(new Scene(root)); } catch (IOException ex) { logger.error("Cannot load fxml file", ex); } textFieldResolution.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { voxelSpacePanelVoxelizationController.setResolution(Float.valueOf(newValue)); } }); textFieldResolution.textProperty().addListener(voxelSpacePanelVoxelizationController.getChangeListener()); checkboxUseDTMFilter.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (checkboxUseDTMFilter.isSelected()) { buttonOpenDTMFile.setDisable(false); textfieldDTMPath.setDisable(false); textfieldDTMValue.setDisable(false); checkboxApplyVOPMatrix.setDisable(false); labelDTMValue.setDisable(false); labelDTMPath.setDisable(false); } else { buttonOpenDTMFile.setDisable(true); textfieldDTMPath.setDisable(true); textfieldDTMValue.setDisable(true); checkboxApplyVOPMatrix.setDisable(true); labelDTMValue.setDisable(true); labelDTMPath.setDisable(true); } } }); checkboxUseVopMatrix.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { buttonSetVOPMatrix.setDisable(!newValue); } }); checkboxUsePopMatrix.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue) { checkBoxUseDefaultPopMatrix.setDisable(false); buttonOpenPopMatrixFile.setDisable(false); } else { checkBoxUseDefaultPopMatrix.setDisable(true); buttonOpenPopMatrixFile.setDisable(true); } } }); checkboxUseSopMatrix.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue) { checkBoxUseDefaultSopMatrix.setDisable(false); buttonOpenSopMatrixFile.setDisable(false); } else { checkBoxUseDefaultSopMatrix.setDisable(true); buttonOpenSopMatrixFile.setDisable(true); } } }); checkboxCalculateGroundEnergy.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { if (newValue) { anchorPaneGroundEnergyParameters.setDisable(false); } else { anchorPaneGroundEnergyParameters.setDisable(true); } } }); listviewRxpScans.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<LidarScan>() { @Override public void changed(ObservableValue<? extends LidarScan> observable, LidarScan oldValue, LidarScan newValue) { if (newValue != null) { sopMatrix = newValue.matrix; updateResultMatrix(); } } }); comboboxModeTLS.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { switch (newValue.intValue()) { case 1: case 2: case 3: listviewRxpScans.setDisable(false); checkboxMergeAfter.setDisable(false); textFieldMergedFileName.setDisable(false); disableSopMatrixChoice(false); labelTLSOutputPath.setText("Output path"); break; default: listviewRxpScans.setDisable(true); checkboxMergeAfter.setDisable(true); textFieldMergedFileName.setDisable(true); //disableSopMatrixChoice(true); labelTLSOutputPath.setText("Output file"); } if (newValue.intValue() == 0 || newValue.intValue() == 1) { checkboxEmptyShotsFilter.setDisable(false); } else { checkboxEmptyShotsFilter.setDisable(true); } } }); tabPaneVoxelisation.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) { switch (newValue.intValue()) { case 1: disableSopMatrixChoice(false); disablePopMatrixChoice(false); checkboxEmptyShotsFilter.setDisable(false); break; default: disableSopMatrixChoice(true); disablePopMatrixChoice(true); checkboxEmptyShotsFilter.setDisable(true); } switch (newValue.intValue()) { case 0: checkboxCalculateGroundEnergy.setDisable(false); if (checkboxCalculateGroundEnergy.isSelected()) { anchorPaneGroundEnergyParameters.setDisable(true); checkboxCalculateGroundEnergy.setDisable(false); } anchorPaneEchoFiltering.getChildren().set(0, anchorPaneEchoFilteringClassifications); //anchorPaneEchoFilteringClassifications.setVisible(true); anchorpaneBoundingBoxParameters.setDisable(checkboxMultiFiles.isSelected()); hboxAutomaticBBox.setDisable(false); break; default: anchorPaneGroundEnergyParameters.setDisable(true); checkboxCalculateGroundEnergy.setDisable(true); anchorPaneEchoFiltering.getChildren().set(0, anchorPaneEchoFilteringRxp); //anchorPaneEchoFilteringClassifications.setVisible(false); anchorpaneBoundingBoxParameters.setDisable(false); hboxAutomaticBBox.setDisable(true); } } }); int availableCores = Runtime.getRuntime().availableProcessors(); sliderRSPCoresToUse.setMin(1); sliderRSPCoresToUse.setMax(availableCores); sliderRSPCoresToUse.setValue(availableCores); textFieldInputFileALS.setOnDragOver(DragAndDropHelper.dragOverEvent); textFieldTrajectoryFileALS.setOnDragOver(DragAndDropHelper.dragOverEvent); textFieldOutputFileALS.setOnDragOver(DragAndDropHelper.dragOverEvent); textFieldInputFileTLS.setOnDragOver(DragAndDropHelper.dragOverEvent); textFieldOutputFileMerging.setOnDragOver(DragAndDropHelper.dragOverEvent); textfieldDTMPath.setOnDragOver(DragAndDropHelper.dragOverEvent); textFieldOutputFileGroundEnergy.setOnDragOver(DragAndDropHelper.dragOverEvent); listViewTaskList.setOnDragOver(DragAndDropHelper.dragOverEvent); listViewProductsFiles.setOnDragOver(DragAndDropHelper.dragOverEvent); textfieldVoxelFilePathTransmittance.setOnDragOver(DragAndDropHelper.dragOverEvent); textfieldOutputTextFilePath.setOnDragOver(DragAndDropHelper.dragOverEvent); textfieldOutputBitmapFilePath.setOnDragOver(DragAndDropHelper.dragOverEvent); textFieldInputFileALS.setOnDragDropped(new EventHandler<DragEvent>() { @Override public void handle(DragEvent event) { Dragboard db = event.getDragboard(); boolean success = false; if (db.hasFiles() && db.getFiles().size() == 1) { success = true; for (File file : db.getFiles()) { if (file != null) { textFieldInputFileALS.setText(file.getAbsolutePath()); selectALSInputMode(file); } } } event.setDropCompleted(success); event.consume(); } }); textFieldTrajectoryFileALS.setOnDragDropped(new EventHandler<DragEvent>() { @Override public void handle(DragEvent event) { Dragboard db = event.getDragboard(); boolean success = false; if (db.hasFiles() && db.getFiles().size() == 1) { success = true; for (File file : db.getFiles()) { if (file != null) { onTrajectoryFileChoosed(file); } } } event.setDropCompleted(success); event.consume(); } }); textFieldInputFileTLS.setOnDragDropped(new EventHandler<DragEvent>() { @Override public void handle(DragEvent event) { Dragboard db = event.getDragboard(); boolean success = false; if (db.hasFiles() && db.getFiles().size() == 1) { success = true; for (File file : db.getFiles()) { if (file != null) { onInputFileTLSChoosed(file); } } } event.setDropCompleted(success); event.consume(); } }); setDragDroppedSingleFileEvent(textFieldOutputFileALS); setDragDroppedSingleFileEvent(textFieldOutputFileMerging); setDragDroppedSingleFileEvent(textfieldDTMPath); setDragDroppedSingleFileEvent(textFieldOutputFileGroundEnergy); setDragDroppedSingleFileEvent(textfieldVoxelFilePathTransmittance); setDragDroppedSingleFileEvent(textfieldOutputTextFilePath); setDragDroppedSingleFileEvent(textfieldOutputBitmapFilePath); listViewTaskList.setOnDragDropped(new EventHandler<DragEvent>() { @Override public void handle(DragEvent event) { Dragboard db = event.getDragboard(); boolean success = false; if (db.hasFiles()) { success = true; for (File file : db.getFiles()) { addFileToTaskList(file); } } event.setDropCompleted(success); event.consume(); } }); listViewProductsFiles.setOnDragDropped(new EventHandler<DragEvent>() { @Override public void handle(DragEvent event) { Dragboard db = event.getDragboard(); boolean success = false; if (db.hasFiles()) { success = true; for (File file : db.getFiles()) { addFileToProductsList(file); } } event.setDropCompleted(success); event.consume(); } }); listViewProductsFiles.setOnDragDetected(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { Dragboard db = listViewProductsFiles.startDragAndDrop(TransferMode.COPY); ClipboardContent content = new ClipboardContent(); content.putFiles(listViewProductsFiles.getSelectionModel().getSelectedItems()); db.setContent(content); event.consume(); } }); addPointcloudFilterComponent(); checkboxUsePointcloudFilter.selectedProperty().addListener(new ChangeListener<Boolean>() { @Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) { hBoxPointCloudFiltering.setDisable(!newValue); ObservableList<Node> list = vBoxPointCloudFiltering.getChildren(); for (Node n : list) { if (n instanceof PointCloudFilterPaneComponent) { PointCloudFilterPaneComponent panel = (PointCloudFilterPaneComponent) n; panel.disableContent(!newValue); } } buttonAddPointcloudFilter.setDisable(!newValue); } }); //displayGThetaAllDistributions(); }
From source file:snpviewer.SnpViewer.java
@Override public void initialize(URL url, ResourceBundle rb) { labelSplitPane.setDividerPositions(); chromSplitPane.setDividerPositions(); Pane lpane = (Pane) horizontalSplit.getItems().get(0); SplitPane.setResizableWithParent(lpane, false); //mnemonics/shortcuts for menus mainMenu.useSystemMenuBarProperty().set(true); fileMenu.setMnemonicParsing(true);/* w ww.j a va 2s .c o m*/ sampleMenu.setMnemonicParsing(true); goMenu.setMnemonicParsing(true); helpMenu.setMnemonicParsing(true); newProjectMenu.setAccelerator(new KeyCodeCombination(KeyCode.N, KeyCombination.SHORTCUT_DOWN)); loadProjectMenu.setAccelerator(new KeyCodeCombination(KeyCode.L, KeyCombination.SHORTCUT_DOWN)); addAffSampleMenu.setAccelerator( new KeyCodeCombination(KeyCode.A, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN)); addUnSampleMenu.setAccelerator( new KeyCodeCombination(KeyCode.U, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN)); nextChromMenu.setAccelerator(new KeyCodeCombination(KeyCode.EQUALS, KeyCombination.SHORTCUT_DOWN)); prevChromMenu.setAccelerator(new KeyCodeCombination(KeyCode.MINUS, KeyCombination.SHORTCUT_DOWN)); firstChromMenu.setAccelerator(new KeyCodeCombination(KeyCode.DIGIT1, KeyCombination.SHORTCUT_DOWN)); lastChromMenu.setAccelerator(new KeyCodeCombination(KeyCode.DIGIT0, KeyCombination.SHORTCUT_DOWN)); redrawMenu.setAccelerator(new KeyCodeCombination(KeyCode.R, KeyCombination.SHORTCUT_DOWN)); cacheChromsMenu.setAccelerator( new KeyCodeCombination(KeyCode.C, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN)); saveToPngMenu.setAccelerator( new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN)); autoFindRegions.setAccelerator(new KeyCodeCombination(KeyCode.F, KeyCombination.SHORTCUT_DOWN)); //need to disable hideSavedRegionsMenu accelerator for linux - doesn't work for check menus hideSavedRegionsMenu.setAccelerator( new KeyCodeCombination(KeyCode.H, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN)); clearSavedRegionsMenu.setAccelerator( new KeyCodeCombination(KeyCode.X, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN)); displaySavedsRegionsMenu.setAccelerator(new KeyCodeCombination(KeyCode.T, KeyCombination.SHORTCUT_DOWN)); outputSavedRegionsMenu.setAccelerator(new KeyCodeCombination(KeyCode.O, KeyCombination.SHORTCUT_DOWN)); removeSampleMenu.setAccelerator( new KeyCodeCombination(KeyCode.R, KeyCombination.SHORTCUT_DOWN, KeyCombination.SHIFT_DOWN)); //set radio menu item toggle group ArrayList<RadioMenuItem> callQualityRadios = new ArrayList<>( Arrays.asList(noFilteringRadio, filter99, filter95, filter90, filter85)); ToggleGroup callQualityToggle = new ToggleGroup(); for (RadioMenuItem r : callQualityRadios) { r.setToggleGroup(callQualityToggle); } noFilteringRadio.setOnAction(new EventHandler() { @Override public void handle(Event ev) { setQualityFilter(null); } }); filter99.setOnAction(new EventHandler() { @Override public void handle(Event ev) { setQualityFilter(0.01); } }); filter95.setOnAction(new EventHandler() { @Override public void handle(Event ev) { setQualityFilter(0.05); } }); filter90.setOnAction(new EventHandler() { @Override public void handle(Event ev) { setQualityFilter(0.10); } }); filter85.setOnAction(new EventHandler() { @Override public void handle(Event ev) { setQualityFilter(0.15); } }); nextChromMenu.setOnAction(new EventHandler() { @Override public void handle(Event ev) { selectNextChromosome(true); } }); prevChromMenu.setOnAction(new EventHandler() { @Override public void handle(Event ev) { selectNextChromosome(false); } }); firstChromMenu.setOnAction(new EventHandler() { @Override public void handle(Event ev) { if (!cancelButton.isDisabled()) { cancelButton.fire(); } if (!chromosomeSelector.isDisabled()) { chromosomeSelector.getSelectionModel().selectFirst(); } } }); lastChromMenu.setOnAction(new EventHandler() { @Override public void handle(Event ev) { if (!cancelButton.isDisabled()) { cancelButton.fire(); } if (!chromosomeSelector.isDisabled()) { chromosomeSelector.getSelectionModel().selectLast(); } } }); hideSavedRegionsMenu.setOnAction(new EventHandler() { @Override public void handle(Event ev) { showHideSavedRegions(); } }); colorComp.addAll(Arrays.asList(colorComponants)); //selection context menu final ContextMenu scm = new ContextMenu(); final MenuItem scmItem1 = new MenuItem("Display Flanking SNP IDs"); scmItem1.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { /* get coordinates of selection and report back * flanking snp ids and coordinates */ displayFlankingSnpIDs(dragSelectRectangle); } }); final MenuItem scmItem2 = new MenuItem("Write Selected Region to File"); scmItem2.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { Platform.runLater(new Runnable() { @Override public void run() { /* get coordinates of selection and report back * write SNPs in region to file */ writeRegionToFile(dragSelectRectangle); } }); } }); final MenuItem scmItem3 = new MenuItem("Add To Saved Regions"); scmItem3.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { /* get coordinates of selection and report back * write SNPs in region to file */ saveSelection(); } }); final MenuItem scmItem4 = new MenuItem("Show/Hide Saved Regions"); scmItem4.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { /* get coordinates of selection and report back * write SNPs in region to file */ hideSavedRegionsMenu.selectedProperty().setValue(!hideSavedRegionsMenu.isSelected()); hideSavedRegionsMenu.fire(); } }); final MenuItem scmItem5 = new MenuItem("Zoom Region"); scmItem5.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { Platform.runLater(new Runnable() { @Override public void run() { /* get coordinates of selection and report back * write SNPs in region to file */ zoomRegion(dragSelectRectangle); } }); } }); final MenuItem scmItem6 = new MenuItem("Write Saved Regions to File"); scmItem6.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { Platform.runLater(new Runnable() { @Override public void run() { /* get coordinates of selection and report back * write SNPs in region to file */ writeSavedRegionsToFile(); } }); } }); scm.getItems().add(scmItem1); scm.getItems().add(scmItem2); scm.getItems().add(scmItem3); scm.getItems().add(scmItem4); scm.getItems().add(scmItem5); scm.getItems().add(scmItem6); //overlayPane context menu ocm = new ContextMenu(); final MenuItem ocmItem1 = new MenuItem("Save Image to File"); ocmItem1.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { Platform.runLater(new Runnable() { @Override public void run() { drawPaneToPng(); } }); } }); ocm.getItems().add(ocmItem1); ocm.getItems().add(scmItem4); ocm.getItems().add(scmItem6); //color selections colorComponantSelector.getItems().clear(); colorComponantSelector.getItems().add("AA"); colorComponantSelector.getItems().add("BB"); colorComponantSelector.getItems().add("AB"); colorComponantSelector.getItems().add("Selection Outline"); colorComponantSelector.getItems().add("Selection Fill"); colorComponantSelector.getItems().add("Saved Region Outline"); colorComponantSelector.getItems().add("Saved Region Fill"); colorComponantSelector.getSelectionModel().selectFirst(); colorPicker.setValue(colorComponants[0]); colorComponantSelector.getSelectionModel().selectedIndexProperty() .addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue ov, Number value, Number new_value) { colorPicker.setValue(colorComp.get(new_value.intValue())); colorPicker.fireEvent(new ActionEvent()); } }); colorPicker.setOnAction(new EventHandler() { @Override public void handle(Event t) { if (!colorComp.get(colorComponantSelector.getSelectionModel().getSelectedIndex()) .equals(colorPicker.getValue())) { colorComp.set(colorComponantSelector.getSelectionModel().getSelectedIndex(), colorPicker.getValue()); saveProject(); //colorComponants[colorComponantSelector.getSelectionModel().getSelectedIndex()] = colorPicker.getValue(); if (colorComponantSelector.getSelectionModel().getSelectedIndex() == Colors.fill.value) { dragSelectRectangle.setFill(colorPicker.getValue()); } else if (colorComponantSelector.getSelectionModel().getSelectedIndex() == Colors.line.value) { dragSelectRectangle.setStroke(colorPicker.getValue()); } else if (colorComponantSelector.getSelectionModel() .getSelectedIndex() == Colors.saveLine.value) { for (Rectangle r : savedRegionsDisplay) { r.setStroke(colorPicker.getValue()); } } else if (colorComponantSelector.getSelectionModel() .getSelectedIndex() == Colors.saveFill.value) { for (Rectangle r : savedRegionsDisplay) { r.setFill(colorPicker.getValue()); } } else { removeSavedChromosomeImages(); if (redrawCheckBox.isSelected()) { refreshView(null, true); } } } } }); /*perform appropriate action when user selects a chromosome * from the chromosome choice box */ chromosomeSelector.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue ov, Number value, Number new_value) { chromosomeBoxList = chromosomeSelector.getItems().toArray(); if (new_value.intValue() > -1) { chromosomeSelected((String) chromosomeBoxList[new_value.intValue()]); } } }); chromosomeSelector.addEventFilter(KeyEvent.ANY, new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent ke) { if (ke.getCode() == KeyCode.UP) { ke.consume(); chromosomeSelector.show(); } } }); selectionOverlayPane.heightProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observableValue, Number oldSceneWidth, Number newSceneWidth) { windowResized(new ActionEvent()); } }); selectionOverlayPane.widthProperty().addListener(new ChangeListener<Number>() { @Override public void changed(ObservableValue<? extends Number> observableValue, Number oldSceneWidth, Number newSceneWidth) { windowResized(new ActionEvent()); } }); /*upon addition of a new affected file adjust components accordingly * i.e. ensure appropriate chromosomes are in the choice box * adjust the split panes to fit all files and redisplay */ affObserve.addListener(new ListChangeListener() { @Override public void onChanged(ListChangeListener.Change change) { change.next();/*from the javadoc * 'Go to the next change. In initial state is invalid a require * a call to next() before calling other methods. The first * next() call will make this object represent the first change. */ if (change.getRemovedSize() > 0) { List<SnpFile> both = new ArrayList<>(unFiles); both.addAll(affFiles); recheckChromosomeSelector(both);//need to check all files again, not just affFiles } else if (change.getAddedSize() > 0) { addToChromosomeSelector(affFiles); } } }); /*as above * but for unaffected files */ unObserve.addListener(new ListChangeListener() { @Override public void onChanged(ListChangeListener.Change change) { change.next(); if (change.getRemovedSize() > 0) { List<SnpFile> both = new ArrayList<>(unFiles); both.addAll(affFiles); recheckChromosomeSelector(both);//need to check all files again, not just unFiles } else if (change.getAddedSize() > 0) { addToChromosomeSelector(unFiles); } } }); selectionOverlayPane.addEventHandler(MouseEvent.MOUSE_MOVED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent e) { if (!genomeVersion.equals("") && chromosomeSelector.getSelectionModel().getSelectedIndex() > -1) { try { ChromosomeLength chromLength = new ChromosomeLength(genomeVersion); String currentChrom = (String) chromosomeBoxList[chromosomeSelector.getSelectionModel() .getSelectedIndex()]; double coordinate = chromLength.getLength(currentChrom) / chromSplitPane.getWidth() * e.getX(); positionIndicator.setText(nf.format(coordinate)); } catch (Exception ex) { positionIndicator.setText("Build Error!"); } } } }); /*handle mouse dragging and effect on dragSelectRectangle * */ dragSelectRectangle.widthProperty().bind(dragSelectRectX.subtract(dragSelectRectInitX)); dragSelectRectangle.heightProperty().bind(selectionOverlayPane.heightProperty()); //dragSelectRectangle.strokeProperty().set(colorComponants[Colors.line.value]); dragSelectRectangle.setStrokeWidth(4.0); //dragSelectRectangle.setBlendMode(BlendMode.SCREEN); dragSelectRectangle.setOpacity(0.45); dragSelectRectangle.setVisible(false); selectionOverlayPane.getChildren().add(dragSelectRectangle); selectionOverlayPane.addEventHandler(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent e) { if (scm.isShowing()) { scm.hide(); } if (!e.isPrimaryButtonDown()) { if (e.isSecondaryButtonDown()) { //check we're not overlapping selection if (e.getX() >= dragSelectRectangle.getX() && e.getX() <= (dragSelectRectangle.getX() + dragSelectRectangle.getWidth())) { return; } //check we're not overlapping saved regions for (Rectangle r : savedRegionsDisplay) { if (r.isVisible() && e.getX() >= r.getX() && e.getX() <= r.getX() + r.getWidth()) { return; } } if (chromosomeSelector.getSelectionModel().isEmpty()) { ocmItem1.setDisable(true); } else { ocmItem1.setDisable(false); } ocm.show(selectionOverlayPane, e.getScreenX(), e.getScreenY()); return; } } if (ocm.isShowing()) { ocm.hide(); } dragSelectRectangle.strokeProperty().set(colorComp.get(Colors.line.value)); dragSelectRectangle.fillProperty().set(colorComp.get(Colors.fill.value)); dragSelectRectX.set(0); dragSelectRectangle.setVisible(true); dragSelectRectangle.setX(e.getX()); dragSelectRectangle.setY(0); dragSelectRectInitX.set(e.getX()); anchorInitX.set(e.getX()); } }); selectionOverlayPane.addEventHandler(MouseEvent.MOUSE_DRAGGED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent e) { if (!e.isPrimaryButtonDown()) { return; } dragSelectRectangle.setVisible(true); if (e.getX() > anchorInitX.doubleValue()) {//dragging to the right if (e.getX() <= selectionOverlayPane.getLayoutX() + selectionOverlayPane.getWidth()) { //mouse is before the edge of the pane dragSelectRectInitX.set(anchorInitX.doubleValue()); dragSelectRectX.set(e.getX()); } else { //mouse is over the edge dragSelectRectX.set(selectionOverlayPane.getWidth()); } } else { if (e.getX() > selectionOverlayPane.getLayoutX()) { dragSelectRectInitX.set(e.getX()); dragSelectRectangle.setX(e.getX()); dragSelectRectX.set(anchorInitX.doubleValue()); } else { dragSelectRectInitX.set(0); dragSelectRectangle.setX(0); /* the two lines below are just to trigger * dragSelectRectangle.widthProperty listener * so that start coordinate changes to 1 */ dragSelectRectX.set(anchorInitX.doubleValue() + 1); dragSelectRectX.set(anchorInitX.doubleValue() + 1); } } } }); selectionOverlayPane.addEventHandler(MouseEvent.MOUSE_RELEASED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent e) { //dragSelectRectX.set(e.getX()); if (!e.isPrimaryButtonDown()) { return; } dragSelectRectangle.setVisible(true); if (dragSelectRectangle.getWidth() == 0) { clearDragSelectRectangle(); } } }); dragSelectRectangle.widthProperty().addListener(new ChangeListener() { @Override public void changed(ObservableValue observableValue, Object oldValue, Object newRectWidth) { if (!genomeVersion.equals("") && chromosomeSelector.getSelectionModel().getSelectedIndex() > -1 && dragSelectRectangle.getWidth() > 0) { try { ChromosomeLength chromLength = new ChromosomeLength(genomeVersion); String currentChrom = (String) chromosomeBoxList[chromosomeSelector.getSelectionModel() .getSelectedIndex()]; double startCoordinate = chromLength.getLength(currentChrom) / selectionOverlayPane.getWidth() * dragSelectRectangle.getX(); double selectionWidth = chromLength.getLength(currentChrom) / selectionOverlayPane.getWidth() * dragSelectRectangle.getWidth(); if (dragSelectRectangle.getX() == 0) { startCoordinate = 1; } selectionIndicator.setText("chr" + currentChrom + ":" + nf.format(startCoordinate) + "-" + nf.format(startCoordinate + selectionWidth)); } catch (Exception ex) { selectionIndicator.setText("Build Error!"); } } else { selectionIndicator.setText(""); } } }); dragSelectRectangle.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent e) { if (e.getButton() == MouseButton.SECONDARY) { if (chromosomeSelector.getSelectionModel().isEmpty()) { scmItem1.setDisable(true); scmItem2.setDisable(true); } else { scmItem1.setDisable(false); scmItem2.setDisable(false); } if (ocm.isShowing()) { ocm.hide(); } scm.show(selectionOverlayPane, e.getScreenX(), e.getScreenY()); } } }); }