Example usage for javafx.scene.control MenuItem MenuItem

List of usage examples for javafx.scene.control MenuItem MenuItem

Introduction

In this page you can find the example usage for javafx.scene.control MenuItem MenuItem.

Prototype

public MenuItem(String text) 

Source Link

Document

Constructs a MenuItem and sets the display text with the specified text

Usage

From source file:be.makercafe.apps.makerbench.Main.java

/**
 * Creates the menubar//from   www. j  a v  a2s  . c  o m
 *
 * @return
 */
private MenuBar createMenuBar() {
    MenuBar bar = new MenuBar();
    Menu projectMenu = new Menu("Project");
    MenuItem openProject = new MenuItem("Open...");
    openProject.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            directoryChooser.setTitle("Please choose a project folder");
            File file = directoryChooser.showDialog(stage);

            viewer.setRoot(setRootFolder(file));

        }
    });
    Menu newProject = new Menu("New");

    MenuItem newFolder = new MenuItem("Folder...");
    newFolder.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            TextInputDialog dialog = new TextInputDialog("my_project_folder");
            dialog.setTitle("New folder");
            dialog.setHeaderText("Create a new folder");
            dialog.setContentText("Folder name:");
            Optional<String> result = dialog.showAndWait();
            if (result.isPresent()) {
                String homeDir = System.getProperty("user.home");

                System.out.println("Folder name: " + result.get());
                System.out.println("User home: " + homeDir);
            }
        }
    });
    newProject.getItems().add(newFolder);

    MenuItem importProject = new MenuItem("Import");
    importProject.setAccelerator(new KeyCodeCombination(KeyCode.I, KeyCombination.CONTROL_DOWN));
    importProject.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            System.out.println("Import");

        }
    });
    MenuItem deleteProject = new MenuItem("Delete");
    deleteProject.setAccelerator(new KeyCodeCombination(KeyCode.D, KeyCombination.CONTROL_DOWN));
    deleteProject.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            System.out.println("Delete");

        }
    });
    projectMenu.getItems().addAll(openProject, newProject, importProject, deleteProject);

    Menu helpMenu = new Menu("Help");

    MenuItem aboutItem = new MenuItem("About");
    aboutItem.setOnAction(new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            Alert alert = new Alert(AlertType.INFORMATION);
            alert.setTitle("Information Dialog");
            alert.setHeaderText("About makerbench");
            alert.setContentText(
                    "Makerbench is an open source IDE for designing and manufacturing objects and code.\nWritten by Luc De pauw\n\nUses opensource libraries from the next projects:\n-RichtextFX by Tomas Mikula\n-JCSG by Michael Hoffer\n-ControlsFX by FXexperience.com");
            alert.showAndWait();
        }
    });

    helpMenu.getItems().add(aboutItem);
    bar.getMenus().addAll(projectMenu, helpMenu);
    return bar;
}

From source file:acmi.l2.clientmod.xdat.Controller.java

private MenuItem createAddMenu(String name, TreeView<Object> elements, TreeItem<Object> selected) {
    ListHolder listHolder = (ListHolder) selected.getValue();

    MenuItem add = new MenuItem(name);
    add.setOnAction(event -> {/* w  w  w .j  a  v a  2  s . c  o m*/
        Stream<ClassHolder> st = SubclassManager.getInstance().getClassWithAllSubclasses(listHolder.type)
                .stream().map(ClassHolder::new);
        List<ClassHolder> list = st.collect(Collectors.toList());

        Optional<ClassHolder> choice;

        if (list.size() == 1) {
            choice = Optional.of(list.get(0));
        } else {
            ChoiceDialog<ClassHolder> cd = new ChoiceDialog<>(list.get(0), list);
            cd.setTitle("Select class");
            cd.setHeaderText(null);
            choice = cd.showAndWait();
        }
        choice.ifPresent(toCreate -> {
            try {
                IOEntity obj = toCreate.clazz.newInstance();

                listHolder.list.add(obj);
                TreeItem<Object> treeItem = createTreeItem(obj);
                selected.getChildren().add(treeItem);
                elements.getSelectionModel().select(treeItem);
                elements.scrollTo(elements.getSelectionModel().getSelectedIndex());

                editor.getHistory().valueCreated(treeItemToScriptString(selected), toCreate.clazz);
            } catch (ReflectiveOperationException e) {
                log.log(Level.WARNING, String.format("Couldn't instantiate %s", toCreate.clazz.getName()), e);
                Dialogs.show(Alert.AlertType.ERROR, "ReflectiveOperationException", null,
                        "Couldn't instantiate " + toCreate.clazz);
            }
        });
    });

    return add;
}

From source file:jp.ac.tohoku.ecei.sb.metabolome.lims.gui.MainWindowController.java

@Override
public void initialize(URL location, ResourceBundle resources) {
    // Table Study
    initializeTable(tableStudy, StudyImpl.class);
    initializeTable(tablePlate, PlateImpl.class);
    initializeTable(tableSample, SampleImpl.class);
    initializeTable(tableInjection, InjectionImpl.class);
    initializeTable(tableCompound, CompoundImpl.class);
    initializeTable(tableHistory, OperationHistoryImpl.class);

    menuBar.setUseSystemMenuBar(true);/*from w  w  w . ja v  a 2 s  .  co m*/

    commandManager = new CommandManager();
    commandManager.setContext(commandManagerContext);
    final GUICommandPaneFactory commandPaneFactory = new GUICommandPaneFactory(commandManager);
    MetabolomeQC.addCorrectionCommands(commandManager);
    for (Map.Entry<String, Class> commend : commandManager.getCommands().entrySet()) {
        MenuItem menuItem = new MenuItem(commend.getKey());
        menuItem.setText(commend.getKey());
        menuItem.setOnAction(e -> {
            final Stage stage = new Stage();
            stage.initModality(Modality.WINDOW_MODAL);

            Parent guiCommand = commandPaneFactory.getCommandPane(commend.getKey(),
                    (commandEvent, managedCommand) -> {
                        stage.close();
                    });
            BorderPane margins = new BorderPane(guiCommand);
            BorderPane.setMargin(guiCommand, new Insets(10));

            stage.setScene(new Scene(margins));
            stage.initOwner(this.stage);
            stage.showAndWait();
            onRefresh(null);
        });
        correctionMenu.getItems().add(menuItem);
    }

    onRefresh(null);
}

From source file:pl.baczkowicz.mqttspy.ui.NewPublicationController.java

/**
 * Refreshes the list of recent messages shown in the publish button's context menu.
 *//*from w  w w.j a  va 2s  .  c  om*/
private void refreshRecentMessages() {
    // Remove all elements
    while (recentMessagesMenu.getItems().size() > 0) {
        recentMessagesMenu.getItems().remove(0);
    }
    while (saveRecentMessagesMenu.getItems().size() > 0) {
        saveRecentMessagesMenu.getItems().remove(0);
    }

    // Add all elements
    for (final ReceivedMqttMessage message : recentMessages) {
        final String topic = message.getTopic();
        final String payload = message.getPayload().length() > 10
                ? message.getPayload().substring(0, 10) + "..."
                : message.getPayload();
        final String time = TimeUtils.DATE_WITH_SECONDS_SDF.format(message.getDate());

        final String messageText = "Topic = '" + topic + "', payload = '" + payload + "', published at " + time;
        final MenuItem recentMessageItem = new MenuItem(messageText);
        recentMessageItem.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                displayMessage(message);
            }
        });
        recentMessagesMenu.getItems().add(recentMessageItem);

        final MenuItem saveMessageItem = new MenuItem(messageText);
        saveMessageItem.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                saveAsScript(message);
            }
        });
        saveRecentMessagesMenu.getItems().add(saveMessageItem);
    }

    recentMessagesMenu.setDisable(recentMessagesMenu.getItems().size() == 0);
    saveRecentMessagesMenu.setDisable(saveRecentMessagesMenu.getItems().size() == 0);
}

From source file:ipat_fx.FXMLDocumentController.java

@Override
public void initialize(URL url, ResourceBundle rb) {

    contextPath = System.getProperty("user.dir") + "/web/";
    dataPath = contextPath + "/Client Data";
    File index = new File(dataPath);
    if (!index.exists()) {
        index.mkdir();/*from   w w w  . j a  v  a 2 s  .c o  m*/
    } else {
        index.delete();
        if (!index.exists()) {
            index.mkdir();
        }
    }

    File prePopulatedProfilePath = new File(contextPath + "/data/");
    File[] listFiles = prePopulatedProfilePath.listFiles();

    for (File listFile : listFiles) {
        if (listFile.isDirectory()) {
            caseFileArray.add(listFile);
        }
    }

    caseItemArray = new MenuItem[caseFileArray.size()];
    for (int i = 0; i < caseFileArray.size(); i++) {
        File get = caseFileArray.get(i);
        MenuItem menuItem = new MenuItem(get.getName());
        cases.getItems().add(menuItem);
        caseItemArray[i] = menuItem;
    }

    problemDataFolderName = "/" + caseItemArray[0].getText();
    profilePath = new File(contextPath + "/data" + problemDataFolderName + "/Profiles/");
    hintsXML = new File(contextPath + "/data" + problemDataFolderName + "/hints.xml");
    inputFolder = new File(dataPath + "/input/");
    outputFolder = new File(dataPath + "/output/");

    for (MenuItem caseItem : caseItemArray) {
        caseItem.setOnAction(e -> {
            MenuItem mItem = (MenuItem) e.getSource();
            problemDataFolderName = "/" + mItem.getText();
            profilePath = new File(contextPath + "/data" + problemDataFolderName + "/Profiles/");
            hintsXML = new File(contextPath + "/data" + problemDataFolderName + "/hints.xml");
            inputFolder = new File(dataPath + "/input/");
            outputFolder = new File(dataPath + "/output/");
        });
    }
    tabFlag = "byProfile";
}

From source file:com.cdd.bao.editor.EditSchema.java

private MenuItem addMenu(Menu parent, String title, KeyCombination accel) {
    MenuItem item = new MenuItem(title);
    parent.getItems().add(item);// w  ww  .  jav  a  2 s.co m
    if (accel != null)
        item.setAccelerator(accel);
    return item;
}

From source file:com.properned.application.SystemController.java

public void populateRecentFileMenu() {
    logger.info("Loading recent files");

    recentFileMenu.getItems().clear();/*  ww  w .j a v  a 2 s  . c om*/
    List<RecentFile> recentFileList = Preferences.getInstance().getRecentFileList();
    for (final RecentFile recentFile : recentFileList) {
        if (recentFile.getFile().exists()) {
            MenuItem menuItemRecentFile = new MenuItem(recentFile.getFile().getAbsolutePath());
            menuItemRecentFile.setMnemonicParsing(false);
            menuItemRecentFile.setOnAction(new EventHandler<ActionEvent>() {

                @Override
                public void handle(ActionEvent event) {
                    loadFileList(recentFile.getFile());
                }
            });
            recentFileMenu.getItems().add(menuItemRecentFile);
        }
    }
}

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 av a 2 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:com.bekwam.resignator.ResignatorAppMainViewController.java

@FXML
public void initialize() {

    try {//www.j ava 2  s  . c  om

        miHelp.setAccelerator(KeyCombination.keyCombination("F1"));

        cbType.getItems().add(SigningArgumentsType.JAR);
        cbType.getItems().add(SigningArgumentsType.FOLDER);

        cbType.getSelectionModel().select(SigningArgumentsType.JAR);

        cbType.setConverter(new StringConverter<SigningArgumentsType>() {

            @Override
            public String toString(SigningArgumentsType type) {
                return StringUtils.capitalize(StringUtils.lowerCase(String.valueOf(type)));
            }

            @Override
            public SigningArgumentsType fromString(String type) {
                return Enum.valueOf(SigningArgumentsType.class, StringUtils.upperCase(type));
            }

        });

        activeConfiguration.activeProfileProperty().bindBidirectional(activeProfile.profileNameProperty());
        tfSourceFile.textProperty().bindBidirectional(activeProfile.sourceFileFileNameProperty());
        tfTargetFile.textProperty().bindBidirectional(activeProfile.targetFileFileNameProperty());
        ckReplace.selectedProperty().bindBidirectional(activeProfile.replaceSignaturesProperty());
        cbType.valueProperty().bindBidirectional(activeProfile.argsTypeProperty());

        miSave.disableProperty().bind(needsSave.not());

        tfSourceFile.textProperty().addListener(new WeakInvalidationListener(needsSaveListener));
        tfTargetFile.textProperty().addListener(new WeakInvalidationListener(needsSaveListener));
        ckReplace.selectedProperty().addListener(new WeakInvalidationListener(needsSaveListener));
        cbType.valueProperty().addListener(new WeakInvalidationListener(needsSaveListener));

        lblSource.setText(SOURCE_LABEL_JAR);
        lblTarget.setText(TARGET_LABEL_JAR);
        cbType.getSelectionModel().selectedItemProperty().addListener((ov, old_v, new_v) -> {
            if (new_v == SigningArgumentsType.FOLDER) {
                if (!lblSource.getText().equalsIgnoreCase(SOURCE_LABEL_FOLDER)) {
                    lblSource.setText(SOURCE_LABEL_FOLDER);
                }
                if (!lblSource.getText().equalsIgnoreCase(TARGET_LABEL_FOLDER)) {
                    lblTarget.setText(TARGET_LABEL_FOLDER);
                }
            } else {
                if (!lblSource.getText().equalsIgnoreCase(SOURCE_LABEL_JAR)) {
                    lblSource.setText(SOURCE_LABEL_JAR);
                }
                if (!lblSource.getText().equalsIgnoreCase(TARGET_LABEL_JAR)) {
                    lblTarget.setText(TARGET_LABEL_JAR);
                }
            }
        });

        lvProfiles.getSelectionModel().selectedItemProperty().addListener((ov, old_v, new_v) -> {

            if (new_v == null) { // coming from clearSelection or sort
                return;
            }

            if (needsSave.getValue()) {

                Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Discard unsaved profile?");
                alert.setHeaderText("Unsaved profile");
                Optional<ButtonType> response = alert.showAndWait();
                if (!response.isPresent() || response.get() != ButtonType.OK) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("[SELECT] discard canceled");
                    }
                    return;
                }
            }

            if (logger.isDebugEnabled()) {
                logger.debug("[SELECT] nv={}", new_v);
            }
            doLoadProfile(new_v);
        });

        lvProfiles.setCellFactory(TextFieldListCell.forListView());

        Task<Void> t = new Task<Void>() {

            @Override
            protected Void call() throws Exception {

                updateMessage("Loading configuration");
                configurationDS.loadConfiguration();

                if (!configurationDS.isSecured()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("[CALL] config not secured; getting password");
                    }
                    NewPasswordController npc = newPasswordControllerProvider.get();

                    if (logger.isDebugEnabled()) {
                        logger.debug("[INIT TASK] npc id={}", npc.hashCode());
                    }

                    Platform.runLater(() -> {
                        try {
                            npc.showAndWait();
                        } catch (Exception exc) {
                            logger.error("error showing npc", exc);
                        }
                    });

                    synchronized (npc) {
                        try {
                            npc.wait(MAX_WAIT_TIME); // 10 minutes to enter the password
                        } catch (InterruptedException exc) {
                            logger.error("new password operation interrupted", exc);
                        }
                    }

                    if (logger.isDebugEnabled()) {
                        logger.debug("[INIT TASK] npc={}", npc.getHashedPassword());
                    }

                    if (StringUtils.isNotEmpty(npc.getHashedPassword())) {

                        activeConfiguration.setHashedPassword(npc.getHashedPassword());
                        activeConfiguration.setUnhashedPassword(npc.getUnhashedPassword());
                        activeConfiguration.setLastUpdatedDateTime(LocalDateTime.now());
                        configurationDS.saveConfiguration();

                        configurationDS.loadConfiguration();
                        configurationDS.decrypt(activeConfiguration.getUnhashedPassword());

                    } else {

                        Platform.runLater(() -> {
                            Alert noPassword = new Alert(Alert.AlertType.INFORMATION,
                                    "You'll need to provide a password to save your keystore credentials.");
                            noPassword.showAndWait();
                        });

                        return null;
                    }
                } else {

                    PasswordController pc = passwordControllerProvider.get();

                    Platform.runLater(() -> {
                        try {
                            pc.showAndWait();
                        } catch (Exception exc) {
                            logger.error("error showing pc", exc);
                        }
                    });

                    synchronized (pc) {
                        try {
                            pc.wait(MAX_WAIT_TIME); // 10 minutes to enter the password
                        } catch (InterruptedException exc) {
                            logger.error("password operation interrupted", exc);
                        }
                    }

                    Platform.runLater(() -> {

                        if (pc.getStage().isShowing()) { // ended in timeout timeout
                            pc.getStage().hide();
                        }

                        if (pc.wasCancelled() || pc.wasReset() || !pc.doesPasswordMatch()) {

                            if (logger.isDebugEnabled()) {
                                logger.debug("[INIT TASK] was cancelled or the number of retries was exceeded");
                            }

                            String msg = "";
                            if (pc.wasCancelled()) {
                                msg = "You must provide a password to the datastore. Exitting...";
                            } else if (pc.wasReset()) {
                                msg = "Data file removed. Exitting...";
                            } else {
                                msg = "Exceeded maximum number of retries. Exitting...";
                            }

                            Alert alert = new Alert(Alert.AlertType.WARNING, msg);
                            alert.setOnCloseRequest((evt) -> {
                                Platform.exit();
                                System.exit(1);
                            });
                            alert.showAndWait();

                        } else {

                            //
                            // save password for later decryption ops
                            //

                            activeConfiguration.setUnhashedPassword(pc.getPassword());
                            configurationDS.decrypt(activeConfiguration.getUnhashedPassword());

                            //
                            // init profileBrowser
                            //
                            if (logger.isDebugEnabled()) {
                                logger.debug("[INIT TASK] loading profiles from source");
                            }

                            long startTimeMillis = System.currentTimeMillis();

                            final List<String> profileNames = configurationDS.getProfiles().stream()
                                    .map(Profile::getProfileName).sorted((o1, o2) -> o1.compareToIgnoreCase(o2))
                                    .collect(Collectors.toList());

                            final List<String> recentProfiles = configurationDS.getRecentProfileNames();

                            if (logger.isDebugEnabled()) {
                                logger.debug("[INIT TASK] loading profiles into UI");
                            }

                            lvProfiles.setItems(FXCollections.observableArrayList(profileNames));

                            if (CollectionUtils.isNotEmpty(recentProfiles)) {
                                mRecentProfiles.getItems().clear();
                                mRecentProfiles.getItems().addAll(
                                        FXCollections.observableArrayList(recentProfiles.stream().map((s) -> {
                                            MenuItem mi = new MenuItem(s);
                                            mi.setOnAction(recentProfileLoadHandler);
                                            return mi;
                                        }).collect(Collectors.toList())));
                            }

                            //
                            // #31 preload the last active profile
                            //
                            if (StringUtils.isNotEmpty(activeConfiguration.getActiveProfile())) {

                                if (logger.isDebugEnabled()) {
                                    logger.debug("[INIT TASK] preloading last active profile={}",
                                            activeConfiguration.getActiveProfile());
                                }
                                doLoadProfile(activeConfiguration.getActiveProfile());
                            }

                            long endTimeMillis = System.currentTimeMillis();

                            if (logger.isDebugEnabled()) {
                                logger.debug("[INIT TASK] loading profiles took {} ms",
                                        (endTimeMillis - startTimeMillis));
                            }
                        }
                    });
                }

                return null;
            }

            @Override
            protected void succeeded() {
                super.succeeded();
                updateMessage("");
                lblStatus.textProperty().unbind();
            }

            @Override
            protected void cancelled() {
                super.cancelled();
                logger.error("task cancelled", getException());
                updateMessage("");
                lblStatus.textProperty().unbind();
            }

            @Override
            protected void failed() {
                super.failed();
                logger.error("task failed", getException());
                updateMessage("");
                lblStatus.textProperty().unbind();
            }
        };

        lblStatus.textProperty().bind(t.messageProperty());

        new Thread(t).start();

    } catch (Exception exc) {

        logger.error("can't load configuration", exc);

        String msg = "Verify that the user has access to the directory '" + configFile + "' under "
                + System.getProperty("user.home") + ".";

        Alert alert = new Alert(Alert.AlertType.ERROR, msg);
        alert.setHeaderText("Can't load config file");
        alert.showAndWait();

        Platform.exit();
    }
}

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
 */// w w  w . j  a va  2s .  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());
}