List of usage examples for javafx.scene.control MenuItem setOnAction
public final void setOnAction(EventHandler<ActionEvent> value)
From source file:org.sleuthkit.autopsy.imagegallery.gui.GroupPane.java
private MenuItem createGrpCatMenuItem(final Category cat) { final MenuItem menuItem = new MenuItem(cat.getDisplayName(), new ImageView(DrawableAttribute.CATEGORY.getIcon())); menuItem.setOnAction(new EventHandler<ActionEvent>() { @Override/*from w w w.j a v a 2 s. c o m*/ public void handle(ActionEvent t) { Set<Long> fileIdSet = new HashSet<>(getGrouping().fileIds()); new CategorizeAction().addTagsToFiles(cat.getTagName(), "", fileIdSet); grpCatSplitMenu.setText(cat.getDisplayName()); grpCatSplitMenu.setOnAction(this); } }); return menuItem; }
From source file:org.sleuthkit.autopsy.imageanalyzer.gui.GroupPane.java
private MenuItem createGrpCatMenuItem(final Category cat) { final MenuItem menuItem = new MenuItem(cat.getDisplayName(), new ImageView(DrawableAttribute.CATEGORY.getIcon())); menuItem.setOnAction(new EventHandler<ActionEvent>() { @Override/*from ww w.java 2 s. c om*/ public void handle(ActionEvent t) { selectAllFiles(); new CategorizeAction().addTag(cat.getTagName(), ""); grpCatSplitMenu.setText(cat.getDisplayName()); grpCatSplitMenu.setOnAction(this); } }); return menuItem; }
From source file:io.github.mzmine.modules.plots.msspectrum.MsSpectrumPlotWindowController.java
public void handleContextMenuShowing(ContextMenuEvent event) { // Calculate the m/z value of the clicked point final double clickedX = event.getX(); XYPlot plot = chartNode.getChart().getXYPlot(); Rectangle2D chartArea = chartNode.getRenderingInfo().getPlotInfo().getDataArea(); RectangleEdge axisEdge = plot.getDomainAxisEdge(); ValueAxis domainAxis = plot.getDomainAxis(); final double clickedMz = domainAxis.java2DToValue(clickedX, chartArea, axisEdge); final double clickedMzWithShift = Math.abs(clickedMz - mzShift.get()); // Update the m/z shift menu item DecimalFormat mzFormat = MZmineCore.getConfiguration().getMZFormat(); setToMenuItem.setText("Set to " + mzFormat.format(clickedMz) + " m/z"); setToMenuItem.setUserData(clickedMz); // Update the Show XIC menu item showXICMenuItem.setText("Show XIC of " + mzFormat.format(clickedMzWithShift) + " m/z"); showXICMenuItem.setUserData(clickedMzWithShift); // Update the MS/MS menu findMSMSMenu.setText("Find MS/MS of " + mzFormat.format(clickedMzWithShift) + " m/z"); final ObservableList<MenuItem> msmsItems = findMSMSMenu.getItems(); msmsItems.clear();/*from w ww . ja v a2 s .c o m*/ MZmineProject project = MZmineCore.getCurrentProject(); for (RawDataFile file : project.getRawDataFiles()) { scans: for (MsScan scan : file.getScans()) { if (scan.getMsFunction().getMsLevel() == 1) continue; for (IsolationInfo isolation : scan.getIsolations()) { if (!isolation.getIsolationMzRange().contains(clickedMzWithShift)) continue; String menuLabel = MsScanUtils.createSingleLineMsScanDescription(scan, isolation); MenuItem msmsItem = new MenuItem(menuLabel); msmsItem.setOnAction(e -> MsSpectrumPlotModule.showNewSpectrumWindow(scan)); msmsItems.add(msmsItem); continue scans; } } } if (msmsItems.isEmpty()) { MenuItem noneItem = new MenuItem("None"); noneItem.setDisable(true); msmsItems.add(noneItem); } // Update the Remove... menu final ObservableList<MenuItem> rmItems = removeDatasetMenu.getItems(); rmItems.clear(); for (MsSpectrumDataSet dataset : datasets) { MenuItem msmsItem = new MenuItem(dataset.getName()); msmsItem.setOnAction(e -> datasets.remove(dataset)); rmItems.add(msmsItem); } removeDatasetMenu.setDisable(rmItems.isEmpty()); }
From source file:org.nmrfx.processor.gui.MainApp.java
MenuBar makeMenuBar(String appName) { MenuToolkit tk = null;//from w ww .j a v a2 s . com if (isMac()) { tk = MenuToolkit.toolkit(); } MenuBar menuBar = new MenuBar(); // Application Menu // TBD: services menu Menu appMenu = new Menu(appName); // Name for appMenu can't be set at // Runtime MenuItem aboutItem = null; Stage aboutStage = makeAbout(appName); if (tk != null) { aboutItem = tk.createAboutMenuItem(appName, aboutStage); } else { aboutItem = new MenuItem("About..."); aboutItem.setOnAction(e -> aboutStage.show()); } MenuItem prefsItem = new MenuItem("Preferences..."); MenuItem quitItem; prefsItem.setOnAction(e -> showPreferences(e)); if (tk != null) { quitItem = tk.createQuitMenuItem(appName); appMenu.getItems().addAll(aboutItem, new SeparatorMenuItem(), prefsItem, new SeparatorMenuItem(), tk.createHideMenuItem(appName), tk.createHideOthersMenuItem(), tk.createUnhideAllMenuItem(), new SeparatorMenuItem(), quitItem); // createQuitMeneItem doesn't result in stop or quit being called // therefore we can't check for waiting till a commit is done before leaving // so explicitly set action to quit quitItem.setOnAction(e -> quit()); } else { quitItem = new MenuItem("Quit"); quitItem.setOnAction(e -> quit()); } // File Menu (items TBD) Menu fileMenu = new Menu("File"); MenuItem openMenuItem = new MenuItem("Open and Draw..."); openMenuItem.setOnAction(e -> FXMLController.getActiveController().openAction(e)); MenuItem addMenuItem = new MenuItem("Open..."); addMenuItem.setOnAction(e -> FXMLController.getActiveController().addNoDrawAction(e)); MenuItem newMenuItem = new MenuItem("New Window..."); newMenuItem.setOnAction(e -> newGraphics(e)); Menu recentMenuItem = new Menu("Open and Draw Recent"); List<Path> recentDatasets = PreferencesController.getRecentDatasets(); for (Path path : recentDatasets) { int count = path.getNameCount(); int first = count - 3; first = first >= 0 ? first : 0; Path subPath = path.subpath(first, count); MenuItem datasetMenuItem = new MenuItem(subPath.toString()); datasetMenuItem .setOnAction(e -> FXMLController.getActiveController().openFile(path.toString(), false, false)); recentMenuItem.getItems().add(datasetMenuItem); } MenuItem pdfMenuItem = new MenuItem("Export PDF..."); pdfMenuItem.setOnAction(e -> FXMLController.getActiveController().exportPDFAction(e)); MenuItem svgMenuItem = new MenuItem("Export SVG..."); svgMenuItem.setOnAction(e -> FXMLController.getActiveController().exportSVGAction(e)); MenuItem loadPeakListMenuItem = new MenuItem("Load PeakLists"); loadPeakListMenuItem.setOnAction(e -> loadPeakLists()); Menu projectMenu = new Menu("Projects"); MenuItem projectOpenMenuItem = new MenuItem("Open..."); projectOpenMenuItem.setOnAction(e -> loadProject()); MenuItem projectSaveAsMenuItem = new MenuItem("Save As..."); projectSaveAsMenuItem.setOnAction(e -> saveProjectAs()); MenuItem projectSaveMenuItem = new MenuItem("Save"); projectSaveMenuItem.setOnAction(e -> saveProject()); Menu recentProjectMenuItem = new Menu("Open Recent"); List<Path> recentProjects = PreferencesController.getRecentProjects(); for (Path path : recentProjects) { int count = path.getNameCount(); int first = count - 3; first = first >= 0 ? first : 0; Path subPath = path.subpath(first, count); MenuItem projectMenuItem = new MenuItem(subPath.toString()); projectMenuItem.setOnAction(e -> loadProject(path)); recentProjectMenuItem.getItems().add(projectMenuItem); } projectMenu.getItems().addAll(projectOpenMenuItem, recentProjectMenuItem, projectSaveMenuItem, projectSaveAsMenuItem); fileMenu.getItems().addAll(openMenuItem, addMenuItem, newMenuItem, recentMenuItem, new SeparatorMenuItem(), pdfMenuItem, svgMenuItem, loadPeakListMenuItem); Menu spectraMenu = new Menu("Spectra"); MenuItem deleteItem = new MenuItem("Delete Spectrum"); deleteItem.setOnAction(e -> FXMLController.getActiveController().removeChart()); MenuItem syncMenuItem = new MenuItem("Sync Axes"); syncMenuItem.setOnAction(e -> PolyChart.activeChart.syncSceneMates()); Menu arrangeMenu = new Menu("Arrange"); MenuItem horizItem = new MenuItem("Horizontal"); horizItem.setOnAction( e -> FXMLController.getActiveController().arrange(FractionPane.ORIENTATION.HORIZONTAL)); MenuItem vertItem = new MenuItem("Vertical"); vertItem.setOnAction(e -> FXMLController.getActiveController().arrange(FractionPane.ORIENTATION.VERTICAL)); MenuItem gridItem = new MenuItem("Grid"); gridItem.setOnAction(e -> FXMLController.getActiveController().arrange(FractionPane.ORIENTATION.GRID)); MenuItem overlayItem = new MenuItem("Overlay"); overlayItem.setOnAction(e -> FXMLController.getActiveController().overlay()); MenuItem minimizeItem = new MenuItem("Minimize Borders"); minimizeItem.setOnAction(e -> FXMLController.getActiveController().setBorderState(true)); MenuItem normalizeItem = new MenuItem("Normal Borders"); normalizeItem.setOnAction(e -> FXMLController.getActiveController().setBorderState(false)); arrangeMenu.getItems().addAll(horizItem, vertItem, gridItem, overlayItem, minimizeItem, normalizeItem); MenuItem alignMenuItem = new MenuItem("Align Spectra"); alignMenuItem.setOnAction(e -> FXMLController.getActiveController().alignCenters()); MenuItem analyzeMenuItem = new MenuItem("Analyzer..."); analyzeMenuItem.setOnAction(e -> showAnalyzer(e)); spectraMenu.getItems().addAll(deleteItem, arrangeMenu, syncMenuItem, alignMenuItem, analyzeMenuItem); // Format (items TBD) // Menu formatMenu = new Menu("Format"); // formatMenu.getItems().addAll(new MenuItem("TBD")); // View Menu (items TBD) Menu viewMenu = new Menu("View"); MenuItem dataMenuItem = new MenuItem("Show Datasets"); dataMenuItem.setOnAction(e -> showDatasetsTable(e)); MenuItem consoleMenuItem = new MenuItem("Show Console"); consoleMenuItem.setOnAction(e -> showConsole(e)); MenuItem attrMenuItem = new MenuItem("Show Attributes"); attrMenuItem.setOnAction(e -> FXMLController.getActiveController().showSpecAttrAction(e)); MenuItem procMenuItem = new MenuItem("Show Processor"); procMenuItem.setOnAction(e -> FXMLController.getActiveController().showProcessorAction(e)); MenuItem scannerMenuItem = new MenuItem("Show Scanner"); scannerMenuItem.setOnAction(e -> FXMLController.getActiveController().showScannerAction(e)); viewMenu.getItems().addAll(consoleMenuItem, dataMenuItem, attrMenuItem, procMenuItem, scannerMenuItem); Menu peakMenu = new Menu("Peaks"); MenuItem peakAttrMenuItem = new MenuItem("Show Peak Tool"); peakAttrMenuItem.setOnAction(e -> FXMLController.getActiveController().showPeakAttrAction(e)); MenuItem peakNavigatorMenuItem = new MenuItem("Show Peak Navigator"); peakNavigatorMenuItem.setOnAction(e -> FXMLController.getActiveController().showPeakNavigator()); MenuItem linkPeakDimsMenuItem = new MenuItem("Link by Labels"); linkPeakDimsMenuItem.setOnAction(e -> FXMLController.getActiveController().linkPeakDims()); MenuItem peakSliderMenuItem = new MenuItem("Show Peak Slider"); peakSliderMenuItem.setOnAction(e -> FXMLController.getActiveController().showPeakSlider()); peakMenu.getItems().addAll(peakAttrMenuItem, peakNavigatorMenuItem, linkPeakDimsMenuItem, peakSliderMenuItem); // Window Menu // TBD standard window menu items // Help Menu (items TBD) Menu helpMenu = new Menu("Help"); MenuItem webSiteMenuItem = new MenuItem("NMRFx Web Site"); webSiteMenuItem.setOnAction(e -> showWebSiteAction(e)); MenuItem docsMenuItem = new MenuItem("Online Documentation"); docsMenuItem.setOnAction(e -> showDocAction(e)); MenuItem versionMenuItem = new MenuItem("Check Version"); versionMenuItem.setOnAction(e -> showVersionAction(e)); MenuItem mailingListItem = new MenuItem("Mailing List Site"); mailingListItem.setOnAction(e -> showMailingListAction(e)); MenuItem refMenuItem = new MenuItem("NMRFx Publication"); refMenuItem.setOnAction(e -> { MainApp.hostServices.showDocument("http://link.springer.com/article/10.1007/s10858-016-0049-6"); }); // home // mailing list // helpMenu.getItems().addAll(docsMenuItem, webSiteMenuItem, mailingListItem, versionMenuItem, refMenuItem); if (tk != null) { Menu windowMenu = new Menu("Window"); windowMenu.getItems().addAll(tk.createMinimizeMenuItem(), tk.createZoomMenuItem(), tk.createCycleWindowsItem(), new SeparatorMenuItem(), tk.createBringAllToFrontItem()); menuBar.getMenus().addAll(appMenu, fileMenu, projectMenu, spectraMenu, viewMenu, peakMenu, windowMenu, helpMenu); tk.autoAddWindowMenuItems(windowMenu); tk.setGlobalMenuBar(menuBar); } else { fileMenu.getItems().add(prefsItem); fileMenu.getItems().add(quitItem); menuBar.getMenus().addAll(fileMenu, projectMenu, spectraMenu, viewMenu, peakMenu, helpMenu); helpMenu.getItems().add(0, aboutItem); } return menuBar; }
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 ww w.j a va 2 s .c om*/ @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: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 ww . j a va 2 s .com*/ @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:open.dolphin.client.MainWindowController.java
/** * Initializes the controller class.// w ww . j av a 2s . c o m * * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { //- Init TableView ReceptView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); PatientSearchView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); PatientFutureView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); LabRecieverView.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY); // mainTab.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() { // @Override // public void changed(ObservableValue<? extends Number> ov, Number oldValue, Number newValue) { // SingleSelectionModel<Tab> selectionModel = mainTab.getSelectionModel(); // if(mainTab.getTabs() != null){ // if(selectionModel.isSelected(0)){ // karteTabPane.getTabs().clear(); // } // } // } // }); // ????? TableColumn colId = new TableColumn("ID"); recept.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("recept")); visitTime.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("visitTime")); tableCellAlignRight(visitTime); clientId.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("clientId")); name.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("name")); sex.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("sex")); tableCellAlignCenter(sex); insurance.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("insurance")); birthDay.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("birthDay")); physicianInCharge.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("physicianInCharge")); clinicalDepartments .setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("clinicalDepartments")); reservation.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("reservation")); memo.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("memo")); status.setCellValueFactory(new PropertyValueFactory<ReceptInfo, String>("status")); tableCellImageAlignCenter(status); // ???? ReceptView.getItems().setAll(fetchDataFromServer()); // ???(?) ReceptView.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) { if (mouseEvent.getClickCount() == 2) { System.out.println("Double clicked"); ReceptInfo selectedUser = ((TableView<ReceptInfo>) mouseEvent.getSource()) .getSelectionModel().getSelectedItem(); // ?????????? for (ReceptInfo info : receptList) { if (info.getName().equals(selectedUser.getName())) { return; } } System.out.println(selectedUser.getClientId()); receptList.add(selectedUser); // ?? final ContextMenu contextMenu = new ContextMenu(); MenuItem item1 = new MenuItem("?"); item1.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { System.out.println("Reserve Karte?"); // ?? // e.getSource(); } }); MenuItem item2 = new MenuItem("???"); item2.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { System.out.println("Close Tab and Preservation???"); karteTabPane.getTabs().remove(karteTabPane.getSelectionModel().getSelectedItem()); // ?? // e.getSource(); } }); MenuItem item3 = new MenuItem("?"); item3.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { System.out.println("Close Tab?"); karteTabPane.getTabs().remove(karteTabPane.getSelectionModel().getSelectedItem()); // ?? // e.getSource(); } }); contextMenu.getItems().addAll(item1, item2, item3); Tab tab = new Tab(selectedUser.getName()); tab.setOnClosed(new EventHandler<Event>() { @Override public void handle(Event t) { Tab tab = (Tab) t.getSource(); for (int i = 0; i < receptList.size(); i++) { if (tab.getText().equals(receptList.get(i).getName())) { receptList.remove(i); } } System.out.println("Closed!"); } }); tab.setContextMenu(contextMenu); // Right-click mouse button menu try { // Loading content on demand Parent root = (Parent) new FXMLLoader() .load(this.getClass().getResource("/resources/fxml/Karte.fxml").openStream()); tab.setContent(root); karteTabPane.getSelectionModel().select(tab); karteTabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS); karteTabPane.getTabs().add(tab); karteTabPane.setPrefSize(kartePane.getPrefWidth(), kartePane.getPrefHeight()); kartePane.getChildren().retainAll(); kartePane.getChildren().add(karteTabPane); } catch (IOException ex) { Logger.getLogger(MainWindowController.class.getName()).log(Level.SEVERE, null, ex); } } } } }); // ???? clientId1.setCellValueFactory(new PropertyValueFactory<PatientSearchInfo, String>("clientId1")); name1.setCellValueFactory(new PropertyValueFactory<PatientSearchInfo, String>("name1")); kana1.setCellValueFactory(new PropertyValueFactory<PatientSearchInfo, String>("kana1")); sex1.setCellValueFactory(new PropertyValueFactory<PatientSearchInfo, String>("sex1")); birthDay1.setCellValueFactory(new PropertyValueFactory<PatientSearchInfo, String>("birthDay1")); receiveDay1.setCellValueFactory(new PropertyValueFactory<PatientSearchInfo, String>("receiveDay1")); status1.setCellValueFactory(new PropertyValueFactory<PatientSearchInfo, String>("status1")); // dummy? PatientSearchView.getItems().setAll(fetchDataFromPatientInfo()); // ??(?) PatientSearchView.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) { if (mouseEvent.getClickCount() == 2) { System.out.println("Double clicked"); PatientSearchInfo selectedUser = ((TableView<PatientSearchInfo>) mouseEvent.getSource()) .getSelectionModel().getSelectedItem(); // ?????????? for (PatientSearchInfo info : patientSearchList) { if (info.getName1().equals(selectedUser.getName1())) { return; } } System.out.println(selectedUser.getKana1()); patientSearchList.add(selectedUser); // ?? final ContextMenu contextMenu = new ContextMenu(); MenuItem item1 = new MenuItem("?"); item1.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { System.out.println("Reserve Karte?"); // ?? // e.getSource(); } }); MenuItem item2 = new MenuItem("???"); item2.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { System.out.println("Close Tab and Preservation???"); karteTabPane1.getTabs().remove(karteTabPane1.getSelectionModel().getSelectedItem()); // ?? // e.getSource(); } }); MenuItem item3 = new MenuItem("?"); item3.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { System.out.println("Close Tab?"); karteTabPane1.getTabs().remove(karteTabPane1.getSelectionModel().getSelectedItem()); // ?? // e.getSource(); } }); contextMenu.getItems().addAll(item1, item2, item3); Tab tab = new Tab(selectedUser.getName1()); tab.setOnClosed(new EventHandler<Event>() { @Override public void handle(Event t) { Tab tab = (Tab) t.getSource(); for (int i = 0; i < patientSearchList.size(); i++) { if (tab.getText().equals(patientSearchList.get(i).getName1())) { patientSearchList.remove(i); } } System.out.println("Closed!"); } }); tab.setContextMenu(contextMenu); // Right-click mouse button menu try { // Loading content on demand Parent root = (Parent) new FXMLLoader() .load(this.getClass().getResource("/resources/fxml/Karte.fxml").openStream()); tab.setContent(root); karteTabPane1.getSelectionModel().select(tab); karteTabPane1.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS); karteTabPane1.getTabs().add(tab); karteTabPane1.setPrefSize(kartePane1.getPrefWidth(), kartePane1.getPrefHeight()); kartePane1.getChildren().retainAll(); kartePane1.getChildren().add(karteTabPane1); } catch (IOException ex) { Logger.getLogger(MainWindowController.class.getName()).log(Level.SEVERE, null, ex); } } } } }); // ???? clientId2.setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("clientId2")); name2.setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("name2")); kana2.setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("kana2")); insurance2.setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("insurance2")); sex2.setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("sex2")); birthDay2.setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("birthDay2")); physicianInCharge2 .setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("physicianInCharge2")); clinicalDepartments2 .setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("clinicalDepartments2")); karte2.setCellValueFactory(new PropertyValueFactory<PatientFutureInfo, String>("karte2")); // dummy? PatientFutureView.getItems().setAll(fetchDataFromPatientFutureInfo()); // ??(?) PatientFutureView.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) { if (mouseEvent.getClickCount() == 2) { System.out.println("Double clicked"); PatientFutureInfo selectedUser = ((TableView<PatientFutureInfo>) mouseEvent.getSource()) .getSelectionModel().getSelectedItem(); System.out.println(selectedUser.getName2()); // ?? final ContextMenu contextMenu = new ContextMenu(); MenuItem item1 = new MenuItem("?"); item1.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { System.out.println("Reserve Karte?"); // ?? // e.getSource(); } }); MenuItem item2 = new MenuItem("???"); item2.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { System.out.println("Close Tab and Preservation???"); karteTabPane2.getTabs().remove(karteTabPane2.getSelectionModel().getSelectedItem()); // ?? // e.getSource(); } }); MenuItem item3 = new MenuItem("?"); item3.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { System.out.println("Close Tab?"); karteTabPane2.getTabs().remove(karteTabPane2.getSelectionModel().getSelectedItem()); // ?? // e.getSource(); } }); contextMenu.getItems().addAll(item1, item2, item3); Tab tab = new Tab(selectedUser.getName2()); tab.setContextMenu(contextMenu); // Right-click mouse button menu try { // Loading content on demand Parent root = (Parent) new FXMLLoader() .load(this.getClass().getResource("/resources/fxml/Karte.fxml").openStream()); tab.setContent(root); karteTabPane2.getSelectionModel().select(tab); karteTabPane2.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS); karteTabPane2.getTabs().add(tab); karteTabPane2.setPrefSize(kartePane2.getPrefWidth(), kartePane2.getPrefHeight()); kartePane2.getChildren().retainAll(); kartePane2.getChildren().add(karteTabPane2); } catch (IOException ex) { Logger.getLogger(MainWindowController.class.getName()).log(Level.SEVERE, null, ex); } } } } }); // ????? lab3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("lab3")); clientId3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("clientId3")); kana3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("kana3")); karteKana3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("karteKana3")); sex3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("sex3")); karteSex3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("karteSex3")); sampleGetDay3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("sampleGetDay3")); register3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("register3")); status3.setCellValueFactory(new PropertyValueFactory<LabReceiverInfo, String>("status3")); // dummy? LabRecieverView.getItems().setAll(fetchDataFromLabRecieverInfo()); // ???(?) LabRecieverView.setOnMouseClicked(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent mouseEvent) { if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) { if (mouseEvent.getClickCount() == 2) { System.out.println("Double clicked"); LabReceiverInfo selectedUser = ((TableView<LabReceiverInfo>) mouseEvent.getSource()) .getSelectionModel().getSelectedItem(); System.out.println(selectedUser.getKana3()); // ?? final ContextMenu contextMenu = new ContextMenu(); MenuItem item1 = new MenuItem("?"); item1.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { System.out.println("Reserve Karte?"); // ?? // e.getSource(); } }); MenuItem item2 = new MenuItem("???"); item2.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { System.out.println("Close Tab and Preservation???"); karteTabPane3.getTabs().remove(karteTabPane3.getSelectionModel().getSelectedItem()); // ?? // e.getSource(); } }); MenuItem item3 = new MenuItem("?"); item3.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { System.out.println("Close Tab?"); karteTabPane3.getTabs().remove(karteTabPane3.getSelectionModel().getSelectedItem()); // ?? // e.getSource(); } }); contextMenu.getItems().addAll(item1, item2, item3); Tab tab = new Tab(selectedUser.getKana3()); tab.setContextMenu(contextMenu); // Right-click mouse button menu try { // Loading content on demand Parent root = (Parent) new FXMLLoader() .load(this.getClass().getResource("/resources/fxml/Karte.fxml").openStream()); tab.setContent(root); karteTabPane3.getSelectionModel().select(tab); karteTabPane3.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS); karteTabPane3.getTabs().add(tab); karteTabPane3.setPrefSize(kartePane3.getPrefWidth(), kartePane3.getPrefHeight()); kartePane3.getChildren().retainAll(); kartePane3.getChildren().add(karteTabPane3); } catch (IOException ex) { Logger.getLogger(MainWindowController.class.getName()).log(Level.SEVERE, null, ex); } } } } }); // ??5?????? Timer exeTimer = new Timer(); Calendar cal = Calendar.getInstance(); final int sec = cal.get(Calendar.SECOND); int delay = (60 - sec) * 1000; int interval = 5 * 1000; TimerTask task = new TimerTask() { @Override public void run() { if (!stopFlag) { System.out.println("this is called every 5 seconds on UI thread"); receptUpdate(); } else { this.cancel(); } } }; exeTimer.schedule(task, delay, interval); }
From source file:com.github.drbookings.ui.controller.MainController.java
private void initTableViewContextMenus() { final ContextMenu menu = new ContextMenu(); final MenuItem mi1 = new MenuItem("Delete"); final MenuItem mi2 = new MenuItem("Add"); final MenuItem mi3 = new MenuItem("Modify"); mi1.setOnAction(event -> { Platform.runLater(() -> deleteSelected()); });//from ww w. j a va2 s. com mi2.setOnAction(event -> { Platform.runLater(() -> addBooking()); }); mi3.setOnAction(event -> { Platform.runLater(() -> showModifyBookingDialog()); }); menu.getItems().addAll(mi2, mi1, mi3); tableView.setContextMenu(menu); tableView.addEventHandler(MouseEvent.MOUSE_CLICKED, t -> { if (t.getButton() == MouseButton.SECONDARY) { menu.show(tableView, t.getScreenX(), t.getScreenY()); } }); }
From source file:com.chart.SwingChart.java
/** * // w w w. j a v a 2 s . com * @param name Chart name * @param parent Skeleton parent * @param axes Configuration of axes * @param abcissaName Abcissa name */ public SwingChart(String name, final Skeleton parent, List<AxisChart> axes, String abcissaName) { this.skeleton = parent; this.axes = axes; this.name = name; this.abcissaFormat = NumberFormat.getInstance(Locale.getDefault()); this.ordinateFormat = NumberFormat.getInstance(Locale.getDefault()); plot = new XYPlot(); plot.setBackgroundPaint(scene2awtColor(javafx.scene.paint.Color.web(strChartBackgroundColor))); plot.setDomainGridlinePaint(scene2awtColor(javafx.scene.paint.Color.web(strGridlineColor))); plot.setRangeGridlinePaint(scene2awtColor(javafx.scene.paint.Color.web(strGridlineColor))); plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0)); abcissaAxis = new NumberAxis(abcissaName); ((NumberAxis) abcissaAxis).setAutoRangeIncludesZero(false); abcissaAxis.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 12)); abcissaAxis.setLabelFont(new Font("SansSerif", Font.PLAIN, 12)); abcissaAxis.setLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor))); abcissaAxis.setTickLabelPaint(scene2awtColor(javafx.scene.paint.Color.web(strTickColor))); abcissaAxis.setAutoRange(true); abcissaAxis.setLowerMargin(0.0); abcissaAxis.setUpperMargin(0.0); abcissaAxis.setTickLabelsVisible(true); abcissaAxis.setLabelFont(abcissaAxis.getLabelFont().deriveFont(fontSize)); abcissaAxis.setTickLabelFont(abcissaAxis.getLabelFont().deriveFont(fontSize)); plot.setDomainAxis(abcissaAxis); for (int i = 0; i < axes.size(); i++) { AxisChart categoria = axes.get(i); addAxis(categoria.getName()); for (int j = 0; j < categoria.configSerieList.size(); j++) { SimpleSeriesConfiguration cs = categoria.configSerieList.get(j); addSeries(categoria.getName(), cs); } } chart = new JFreeChart("", new Font("SansSerif", Font.BOLD, 16), plot, false); chart.setBackgroundPaint(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor))); chartPanel = new ChartPanel(chart); chartPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4), BorderFactory.createLineBorder(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor))))); chartPanel.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "escape"); chartPanel.getActionMap().put("escape", new AbstractAction() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { for (int i = 0; i < plot.getDatasetCount(); i++) { XYDataset test = plot.getDataset(i); XYItemRenderer r = plot.getRenderer(i); r.removeAnnotations(); } } }); chartPanel.addChartMouseListener(cml = new ChartMouseListener() { @Override public void chartMouseClicked(ChartMouseEvent event) { } @Override public void chartMouseMoved(ChartMouseEvent event) { try { XYItemEntity xyitem = (XYItemEntity) event.getEntity(); // get clicked entity XYDataset dataset = (XYDataset) xyitem.getDataset(); // get data set double x = dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem()); double y = dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem()); final XYPlot plot = chart.getXYPlot(); for (int i = 0; i < plot.getDatasetCount(); i++) { XYDataset test = plot.getDataset(i); XYItemRenderer r = plot.getRenderer(i); r.removeAnnotations(); if (test == dataset) { NumberAxis ejeOrdenada = AxesList.get(i); double y_max = ejeOrdenada.getUpperBound(); double y_min = ejeOrdenada.getLowerBound(); double x_max = abcissaAxis.getUpperBound(); double x_min = abcissaAxis.getLowerBound(); double angulo; if (y > (y_max + y_min) / 2 && x > (x_max + x_min) / 2) { angulo = 3.0 * Math.PI / 4.0; } else if (y > (y_max + y_min) / 2 && x < (x_max + x_min) / 2) { angulo = 1.0 * Math.PI / 4.0; } else if (y < (y_max + y_min) / 2 && x < (x_max + x_min) / 2) { angulo = 7.0 * Math.PI / 4.0; } else { angulo = 5.0 * Math.PI / 4.0; } CircleDrawer cd = new CircleDrawer((Color) r.getSeriesPaint(xyitem.getSeriesIndex()), new BasicStroke(2.0f), null); //XYAnnotation bestBid = new XYDrawableAnnotation(dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem()), dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem()), 11, 11, cd); String txt = "X:" + abcissaFormat.format(x) + ", Y:" + ordinateFormat.format(y); XYPointerAnnotation anotacion = new XYPointerAnnotation(txt, dataset.getXValue(xyitem.getSeriesIndex(), xyitem.getItem()), dataset.getYValue(xyitem.getSeriesIndex(), xyitem.getItem()), angulo); anotacion.setTipRadius(10.0); anotacion.setBaseRadius(35.0); anotacion.setFont(new Font("SansSerif", Font.PLAIN, 10)); if (Long.parseLong((strChartBackgroundColor.replace("#", "")), 16) > 0xffffff / 2) { anotacion.setPaint(Color.black); anotacion.setArrowPaint(Color.black); } else { anotacion.setPaint(Color.white); anotacion.setArrowPaint(Color.white); } //bestBid.setPaint((Color) r.getSeriesPaint(xyitem.getSeriesIndex())); r.addAnnotation(anotacion); } } //LabelValorVariable.setSize(LabelValorVariable.getPreferredSize()); } catch (NullPointerException | ClassCastException ex) { } } }); chartPanel.setPopupMenu(null); chartPanel.setBackground(scene2awtColor(javafx.scene.paint.Color.web(strBackgroundColor))); SwingNode sn = new SwingNode(); sn.setContent(chartPanel); chartFrame = new VBox(); chartFrame.getChildren().addAll(sn, legendFrame); VBox.setVgrow(sn, Priority.ALWAYS); VBox.setVgrow(legendFrame, Priority.NEVER); chartFrame.getStylesheets().addAll(SwingChart.class.getResource("overlay-chart.css").toExternalForm()); legendFrame.setStyle("marco: " + strBackgroundColor + ";-fx-background-color: marco;"); MenuItem mi; mi = new MenuItem("Print"); mi.setOnAction((ActionEvent t) -> { print(chartFrame); }); contextMenuList.add(mi); sn.setOnMouseClicked((MouseEvent t) -> { if (menu != null) { menu.hide(); } if (t.getClickCount() == 2) { backgroundEdition(); } }); mi = new MenuItem("Copy to clipboard"); mi.setOnAction((ActionEvent t) -> { copyClipboard(chartFrame); }); contextMenuList.add(mi); mi = new MenuItem("Export values"); mi.setOnAction((ActionEvent t) -> { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Export to file"); fileChooser.getExtensionFilters() .addAll(new FileChooser.ExtensionFilter("Comma Separated Values", "*.csv")); Window w = null; try { w = parent.getScene().getWindow(); } catch (NullPointerException e) { } File file = fileChooser.showSaveDialog(w); if (file != null) { export(file); } }); contextMenuList.add(mi); chartFrame.setOnContextMenuRequested((ContextMenuEvent t) -> { if (menu != null) { menu.hide(); } menu = new ContextMenu(); menu.getItems().addAll(contextMenuList); menu.show(chartFrame, t.getScreenX(), t.getScreenY()); }); }
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(); }// ww w .j a v a2s.co m } // 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; }