Example usage for javafx.scene.control TableView getSelectionModel

List of usage examples for javafx.scene.control TableView getSelectionModel

Introduction

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

Prototype

public final TableViewSelectionModel<S> getSelectionModel() 

Source Link

Usage

From source file:Main.java

@Override
public void start(Stage stage) {
    Scene scene = new Scene(new Group());
    stage.setTitle("Table View Sample");
    stage.setWidth(300);//from  w  ww .  ja v a 2 s .c om
    stage.setHeight(500);

    final Label label = new Label("Student IDs");
    label.setFont(new Font("Arial", 20));

    TableColumn<Map, String> firstDataColumn = new TableColumn<>("Class A");
    TableColumn<Map, String> secondDataColumn = new TableColumn<>("Class B");

    firstDataColumn.setCellValueFactory(new MapValueFactory(Column1MapKey));
    firstDataColumn.setMinWidth(130);
    secondDataColumn.setCellValueFactory(new MapValueFactory(Column2MapKey));
    secondDataColumn.setMinWidth(130);

    TableView tableView = new TableView<>(generateDataInMap());

    tableView.setEditable(true);
    tableView.getSelectionModel().setCellSelectionEnabled(true);
    tableView.getColumns().setAll(firstDataColumn, secondDataColumn);
    Callback<TableColumn<Map, String>, TableCell<Map, String>> cellFactoryForMap = (
            TableColumn<Map, String> p) -> new TextFieldTableCell(new StringConverter() {
                @Override
                public String toString(Object t) {
                    return t.toString();
                }

                @Override
                public Object fromString(String string) {
                    return string;
                }
            });
    firstDataColumn.setCellFactory(cellFactoryForMap);
    secondDataColumn.setCellFactory(cellFactoryForMap);

    final VBox vbox = new VBox();

    vbox.setSpacing(5);
    vbox.setPadding(new Insets(10, 0, 0, 10));
    vbox.getChildren().addAll(label, tableView);

    ((Group) scene.getRoot()).getChildren().addAll(vbox);

    stage.setScene(scene);

    stage.show();
}

From source file:com.ggvaidya.scinames.dataset.DatasetSceneController.java

private void fillTableWithChanges(TableView<Change> tv, Dataset tp) {
    // Preserve search order and selected item.
    List<TableColumn<Change, ?>> sortByCols = new LinkedList<>(tv.getSortOrder());
    List<Change> selectedChanges = new LinkedList<>(tv.getSelectionModel().getSelectedItems());

    LOGGER.info("About to set changes table items: sortByCols = " + sortByCols + ", selectedChanges = "
            + selectedChanges);//from   w ww  .  j a  va2s  .  c  o m
    tv.setItems(FXCollections.observableList(tp.getAllChangesAsList()));
    LOGGER.info("tv.setItems() completed");

    for (Change ch : selectedChanges) {
        tv.getSelectionModel().select(ch);
    }
    tv.getSortOrder().addAll(sortByCols);
    LOGGER.info("fillTableWithChanges() completed");
}

From source file:com.ggvaidya.scinames.dataset.DatasetSceneController.java

private void setupTableWithChanges(TableView<Change> tv, Dataset tp) {
    tv.setEditable(true);//from  ww w  .  ja va  2  s  . c o  m
    tv.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    tv.getColumns().clear();

    TableColumn<Change, ChangeType> colChangeType = new TableColumn<>("Type");
    colChangeType.setCellFactory(ComboBoxTableCell.forTableColumn(new ChangeTypeStringConverter(),
            ChangeType.ADDITION, ChangeType.DELETION, ChangeType.RENAME, ChangeType.LUMP, ChangeType.SPLIT,
            ChangeType.COMPLEX, ChangeType.ERROR));
    colChangeType.setCellValueFactory(new PropertyValueFactory<>("type"));
    colChangeType.setPrefWidth(100.0);
    colChangeType.setEditable(true);
    tv.getColumns().add(colChangeType);

    TableColumn<Change, ObservableSet<Name>> colChangeFrom = new TableColumn<>("From");
    colChangeFrom.setCellFactory(TextFieldTableCell.forTableColumn(new NameSetStringConverter()));
    colChangeFrom.setCellValueFactory(new PropertyValueFactory<>("from"));
    colChangeFrom.setPrefWidth(200.0);
    colChangeFrom.setEditable(true);
    tv.getColumns().add(colChangeFrom);

    TableColumn<Change, ObservableSet<Name>> colChangeTo = new TableColumn<>("To");
    colChangeTo.setCellFactory(TextFieldTableCell.forTableColumn(new NameSetStringConverter()));
    colChangeTo.setCellValueFactory(new PropertyValueFactory<>("to"));
    colChangeTo.setPrefWidth(200.0);
    colChangeTo.setEditable(true);
    tv.getColumns().add(colChangeTo);

    TableColumn<Change, String> colExplicit = new TableColumn<>("Explicit or implicit?");
    colExplicit.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    features.getValue().getDataset().isChangeImplicit(features.getValue()) ? "Implicit"
                            : "Explicit"));
    tv.getColumns().add(colExplicit);

    ChangeFilter cf = datasetView.getProjectView().getProject().getChangeFilter();
    TableColumn<Change, String> colFiltered = new TableColumn<>("Eliminated by filter?");
    colFiltered.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    cf.test(features.getValue()) ? "Allowed" : "Eliminated"));
    tv.getColumns().add(colFiltered);

    TableColumn<Change, String> colNote = new TableColumn<>("Note");
    colNote.setCellFactory(TextFieldTableCell.forTableColumn());
    colNote.setCellValueFactory(new PropertyValueFactory<>("note"));
    colNote.setPrefWidth(100.0);
    colNote.setEditable(true);
    tv.getColumns().add(colNote);

    TableColumn<Change, String> colCitations = new TableColumn<>("Citations");
    colCitations.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    features.getValue().getCitationStream().map(citation -> citation.getCitation()).sorted()
                            .collect(Collectors.joining("; "))));
    tv.getColumns().add(colCitations);

    TableColumn<Change, String> colGenera = new TableColumn<>("Genera");
    colGenera.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    String.join(", ", features.getValue().getAllNames().stream().map(n -> n.getGenus())
                            .distinct().sorted().collect(Collectors.toList()))));
    tv.getColumns().add(colGenera);

    TableColumn<Change, String> colSpecificEpithet = new TableColumn<>("Specific epithets");
    colSpecificEpithet.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(String
                    .join(", ", features.getValue().getAllNames().stream().map(n -> n.getSpecificEpithet())
                            .filter(s -> s != null).distinct().sorted().collect(Collectors.toList()))));
    tv.getColumns().add(colSpecificEpithet);

    // The infraspecific string.
    TableColumn<Change, String> colInfraspecificEpithet = new TableColumn<>("Infraspecific epithets");
    colInfraspecificEpithet.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    String.join(", ",
                            features.getValue().getAllNames().stream()
                                    .map(n -> n.getInfraspecificEpithetsAsString()).filter(s -> s != null)
                                    .distinct().sorted().collect(Collectors.toList()))));
    tv.getColumns().add(colInfraspecificEpithet);

    // The very last epithet of all
    TableColumn<Change, String> colTerminalEpithet = new TableColumn<>("Terminal epithet");
    colTerminalEpithet.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    String.join(", ", features.getValue().getAllNames().stream().map(n -> {
                        List<Name.InfraspecificEpithet> infraspecificEpithets = n.getInfraspecificEpithets();
                        if (!infraspecificEpithets.isEmpty()) {
                            return infraspecificEpithets.get(infraspecificEpithets.size() - 1).getValue();
                        } else {
                            return n.getSpecificEpithet();
                        }
                    }).filter(s -> s != null).distinct().sorted().collect(Collectors.toList()))));
    tv.getColumns().add(colTerminalEpithet);

    // Properties
    TableColumn<Change, String> colProperties = new TableColumn<>("Properties");
    colProperties.setCellValueFactory(
            (TableColumn.CellDataFeatures<Change, String> features) -> new ReadOnlyStringWrapper(
                    features.getValue().getProperties().entrySet().stream()
                            .map(entry -> entry.getKey() + ": " + entry.getValue()).sorted()
                            .collect(Collectors.joining("; "))));
    tv.getColumns().add(colProperties);

    fillTableWithChanges(tv, tp);

    // When someone selects a cell in the Table, try to select the appropriate data in the
    // additional data view.
    tv.getSelectionModel().getSelectedItems().addListener((ListChangeListener<Change>) lcl -> {
        AdditionalData aData = additionalDataCombobox.getSelectionModel().getSelectedItem();

        if (aData != null) {
            aData.onSelectChange(tv.getSelectionModel().getSelectedItems());
        }
    });

    // Create a right-click menu for table rows.
    changesTableView.setRowFactory(table -> {
        TableRow<Change> row = new TableRow<>();

        row.setOnContextMenuRequested(event -> {
            if (row.isEmpty())
                return;

            // We don't currently use the clicked change, since currently all options
            // change *all* the selected changes, but this may change in the future.
            Change change = row.getItem();

            ContextMenu changeMenu = new ContextMenu();

            Menu searchForName = new Menu("Search for name");
            searchForName.getItems().addAll(
                    change.getAllNames().stream().sorted().map(n -> createMenuItem(n.getFullName(), action -> {
                        datasetView.getProjectView().openDetailedView(n);
                    })).collect(Collectors.toList()));
            changeMenu.getItems().add(searchForName);
            changeMenu.getItems().add(new SeparatorMenuItem());

            changeMenu.getItems().add(createMenuItem("Edit note", action -> {
                List<Change> changes = new ArrayList<>(changesTableView.getSelectionModel().getSelectedItems());

                String combinedNotes = changes.stream().map(ch -> ch.getNote().orElse("").trim()).distinct()
                        .collect(Collectors.joining("\n")).trim();

                Optional<String> result = askUserForTextArea(
                        "Modify the note for these " + changes.size() + " changes:", combinedNotes);

                if (result.isPresent()) {
                    String note = result.get().trim();
                    LOGGER.info("Using 'Edit note' to set note to '" + note + "' on changes " + changes);
                    changes.forEach(ch -> ch.noteProperty().set(note));
                }
            }));
            changeMenu.getItems().add(new SeparatorMenuItem());

            // Create a submenu for tags and urls.
            String note = change.noteProperty().get();

            Menu removeTags = new Menu("Tags");
            removeTags.getItems().addAll(change.getTags().stream().sorted()
                    .map(tag -> new MenuItem(tag.getName())).collect(Collectors.toList()));

            Menu lookupURLs = new Menu("Lookup URL");
            change.getURIs().stream().sorted().map(uri -> {
                return createMenuItem(uri.toString(), evt -> {
                    try {
                        Desktop.getDesktop().browse(uri);
                    } catch (IOException ex) {
                        LOGGER.warning("Could not open URL '" + uri + "': " + ex);
                    }
                });
            }).forEach(mi -> lookupURLs.getItems().add(mi));
            changeMenu.getItems().add(lookupURLs);

            changeMenu.getItems().add(new SeparatorMenuItem());
            changeMenu.getItems().add(createMenuItem("Prepend text to all notes", action -> {
                List<Change> changes = new ArrayList<>(changesTableView.getSelectionModel().getSelectedItems());

                Optional<String> result = askUserForTextField(
                        "Enter tags to prepend to notes in " + changes.size() + " changes:");

                if (result.isPresent()) {
                    String tags = result.get().trim();
                    changes.forEach(ch -> {
                        String prevValue = change.getNote().orElse("").trim();

                        LOGGER.info("Prepending tags '" + tags + "' to previous value '" + prevValue
                                + "' for change " + ch);

                        ch.noteProperty().set((tags + " " + prevValue).trim());
                    });
                }
            }));
            changeMenu.getItems().add(createMenuItem("Append text to all notes", action -> {
                List<Change> changes = new ArrayList<>(changesTableView.getSelectionModel().getSelectedItems());
                Optional<String> result = askUserForTextField(
                        "Enter tags to append to notes in " + changes.size() + " changes:");

                if (result.isPresent()) {
                    String tags = result.get().trim();
                    changes.forEach(ch -> {
                        String prevValue = ch.getNote().orElse("").trim();

                        LOGGER.info("Appending tags '" + tags + "' to previous value '" + prevValue
                                + "' for change " + ch);

                        ch.noteProperty().setValue((prevValue + " " + tags).trim());
                    });
                }
            }));

            changeMenu.show(datasetView.getScene().getWindow(), event.getScreenX(), event.getScreenY());

        });

        return row;
    });

    LOGGER.info("setupTableWithChanges() completed");
}

From source file:org.simmi.GeneSetHead.java

License:asdf

public void updateFilter(TableView table, Label label) {
    if (label != null)
        label.setText(table.getItems().size() + "/" + table.getSelectionModel().getSelectedIndices().size());
}

From source file:org.simmi.GeneSetHead.java

License:asdf

private static void relati(TableView<Gene> table, List<Gene> genelist, Set<Integer> genefilterset,
        List<Set<String>> uclusterlist, boolean remove) {
    Set<String> ct = new HashSet<String>();
    for (Gene gg : table.getSelectionModel().getSelectedItems()) {
        GeneGroup ggroup = gg.getGeneGroup();
        for (Gene g : ggroup.genes) {
            ct.add(g.refid);/*from  w  w  w  .  j a va 2  s .  c o m*/
        }
        // genefilterset.add( gg.index );
        /*Tegeval tv = gg.tegeval;
           //System.err.println( tv.cont );
           //int li = tv.cont.lastIndexOf('_');
           //String tvshort = tv.contshort+tv.cont.substring(li);
        for (Set<String> uset : uclusterlist) {
           if (uset.contains(tv.cont)) {
              System.err.println( uset );
              ct.addAll(uset);
              break;
           }
        }*/
    }

    for (Gene g : genelist) {
        //Tegeval tv = g.tegeval;
        //System.err.println( tv.cont );
        //int li = tv.cont.lastIndexOf('_');
        //String tvshort = tv.contshort+tv.cont.substring(li);
        if (ct.contains(g.refid)) {
            if (remove)
                genefilterset.remove(genelist.indexOf(g));
            else
                genefilterset.add(genelist.indexOf(g));
            //break;
        }
    }
    System.err.println(genefilterset.size() + "  " + ct.size());
}

From source file:qupath.lib.gui.tma.TMASummaryViewer.java

private Pane getCustomizeTablePane() {
    TableView<TreeTableColumn<TMAEntry, ?>> tableColumns = new TableView<>();
    tableColumns.setPlaceholder(new Text("No columns available"));
    tableColumns.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    tableColumns.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);

    SortedList<TreeTableColumn<TMAEntry, ?>> sortedColumns = new SortedList<>(
            table.getColumns().filtered(p -> !p.getText().trim().isEmpty()));
    sortedColumns.setComparator((c1, c2) -> c1.getText().compareTo(c2.getText()));
    tableColumns.setItems(sortedColumns);
    sortedColumns.comparatorProperty().bind(tableColumns.comparatorProperty());
    //      sortedColumns.comparatorProperty().bind(tableColumns.comparatorProperty());

    TableColumn<TreeTableColumn<TMAEntry, ?>, String> columnName = new TableColumn<>("Column");
    columnName.setCellValueFactory(v -> v.getValue().textProperty());
    TableColumn<TreeTableColumn<TMAEntry, ?>, Boolean> columnVisible = new TableColumn<>("Visible");
    columnVisible.setCellValueFactory(v -> v.getValue().visibleProperty());
    //      columnVisible.setCellValueFactory(col -> {
    //         SimpleBooleanProperty prop = new SimpleBooleanProperty(col.getValue().isVisible());
    //         prop.addListener((v, o, n) -> col.getValue().setVisible(n));
    //         return prop;
    //      });//  ww  w . java 2s . com
    tableColumns.setEditable(true);
    columnVisible.setCellFactory(v -> new CheckBoxTableCell<>());
    tableColumns.getColumns().add(columnName);
    tableColumns.getColumns().add(columnVisible);
    ContextMenu contextMenu = new ContextMenu();

    Action actionShowSelected = new Action("Show selected", e -> {
        for (TreeTableColumn<?, ?> col : tableColumns.getSelectionModel().getSelectedItems()) {
            if (col != null)
                col.setVisible(true);
            else {
                // Not sure why this happens...?
                logger.trace("Selected column is null!");
            }
        }
    });

    Action actionHideSelected = new Action("Hide selected", e -> {
        for (TreeTableColumn<?, ?> col : tableColumns.getSelectionModel().getSelectedItems()) {
            if (col != null)
                col.setVisible(false);
            else {
                // Not sure why this happens...?
                logger.trace("Selected column is null!");
            }
        }
    });

    contextMenu.getItems().addAll(ActionUtils.createMenuItem(actionShowSelected),
            ActionUtils.createMenuItem(actionHideSelected));
    tableColumns.setContextMenu(contextMenu);
    tableColumns.setTooltip(
            new Tooltip("Show or hide table columns - right-click to change multiple columns at once"));

    BorderPane paneColumns = new BorderPane(tableColumns);
    paneColumns.setBottom(PanelToolsFX.createColumnGridControls(ActionUtils.createButton(actionShowSelected),
            ActionUtils.createButton(actionHideSelected)));

    VBox paneRows = new VBox();

    // Create a box to filter on some metadata text
    ComboBox<String> comboMetadata = new ComboBox<>();
    comboMetadata.setItems(metadataNames);
    comboMetadata.getSelectionModel().getSelectedItem();
    comboMetadata.setPromptText("Select column");
    TextField tfFilter = new TextField();
    CheckBox cbExact = new CheckBox("Exact");
    // Set listeners
    cbExact.selectedProperty().addListener(
            (v, o, n) -> setMetadataTextPredicate(comboMetadata.getSelectionModel().getSelectedItem(),
                    tfFilter.getText(), cbExact.isSelected(), !cbExact.isSelected()));
    tfFilter.textProperty().addListener(
            (v, o, n) -> setMetadataTextPredicate(comboMetadata.getSelectionModel().getSelectedItem(),
                    tfFilter.getText(), cbExact.isSelected(), !cbExact.isSelected()));
    comboMetadata.getSelectionModel().selectedItemProperty().addListener(
            (v, o, n) -> setMetadataTextPredicate(comboMetadata.getSelectionModel().getSelectedItem(),
                    tfFilter.getText(), cbExact.isSelected(), !cbExact.isSelected()));

    GridPane paneMetadata = new GridPane();
    paneMetadata.add(comboMetadata, 0, 0);
    paneMetadata.add(tfFilter, 1, 0);
    paneMetadata.add(cbExact, 2, 0);
    paneMetadata.setPadding(new Insets(10, 10, 10, 10));
    paneMetadata.setVgap(2);
    paneMetadata.setHgap(5);
    comboMetadata.setMaxWidth(Double.MAX_VALUE);
    GridPane.setHgrow(tfFilter, Priority.ALWAYS);
    GridPane.setFillWidth(comboMetadata, Boolean.TRUE);
    GridPane.setFillWidth(tfFilter, Boolean.TRUE);

    TitledPane tpMetadata = new TitledPane("Metadata filter", paneMetadata);
    tpMetadata.setExpanded(false);
    //      tpMetadata.setCollapsible(false);
    Tooltip tooltipMetadata = new Tooltip(
            "Enter text to filter entries according to a selected metadata column");
    Tooltip.install(paneMetadata, tooltipMetadata);
    tpMetadata.setTooltip(tooltipMetadata);
    paneRows.getChildren().add(tpMetadata);

    // Add measurement predicate
    TextField tfCommand = new TextField();
    tfCommand.setTooltip(new Tooltip("Predicate used to filter entries for inclusion"));

    TextFields.bindAutoCompletion(tfCommand, e -> {
        int ind = tfCommand.getText().lastIndexOf("\"");
        if (ind < 0)
            return Collections.emptyList();
        String part = tfCommand.getText().substring(ind + 1);
        return measurementNames.stream().filter(n -> n.startsWith(part)).map(n -> "\"" + n + "\" ")
                .collect(Collectors.toList());
    });

    String instructions = "Enter a predicate to filter entries.\n"
            + "Only entries passing the test will be included in any results.\n"
            + "Examples of predicates include:\n" + "    \"Num Tumor\" > 200\n"
            + "    \"Num Tumor\" > 100 && \"Num Stroma\" < 1000";
    //      labelInstructions.setTooltip(new Tooltip("Note: measurement names must be in \"inverted commands\" and\n" + 
    //            "&& indicates 'and', while || indicates 'or'."));

    BorderPane paneMeasurementFilter = new BorderPane(tfCommand);
    Label label = new Label("Predicate: ");
    label.setAlignment(Pos.CENTER);
    label.setMaxHeight(Double.MAX_VALUE);
    paneMeasurementFilter.setLeft(label);

    Button btnApply = new Button("Apply");
    btnApply.setOnAction(e -> {
        TablePredicate predicateNew = new TablePredicate(tfCommand.getText());
        if (predicateNew.isValid()) {
            predicateMeasurements.set(predicateNew);
        } else {
            DisplayHelpers.showErrorMessage("Invalid predicate",
                    "Current predicate '" + tfCommand.getText() + "' is invalid!");
        }
        e.consume();
    });
    TitledPane tpMeasurementFilter = new TitledPane("Measurement filter", paneMeasurementFilter);
    tpMeasurementFilter.setExpanded(false);
    Tooltip tooltipInstructions = new Tooltip(instructions);
    tpMeasurementFilter.setTooltip(tooltipInstructions);
    Tooltip.install(paneMeasurementFilter, tooltipInstructions);
    paneMeasurementFilter.setRight(btnApply);

    paneRows.getChildren().add(tpMeasurementFilter);

    logger.info("Predicate set to: {}", predicateMeasurements.get());

    VBox pane = new VBox();
    //      TitledPane tpColumns = new TitledPane("Select column", paneColumns);
    //      tpColumns.setMaxHeight(Double.MAX_VALUE);
    //      tpColumns.setCollapsible(false);
    pane.getChildren().addAll(paneColumns, new Separator(), paneRows);
    VBox.setVgrow(paneColumns, Priority.ALWAYS);

    return pane;
}