Example usage for javafx.scene.control TableColumn setCellFactory

List of usage examples for javafx.scene.control TableColumn setCellFactory

Introduction

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

Prototype

public final void setCellFactory(Callback<TableColumn<S, T>, TableCell<S, T>> value) 

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 www  .jav  a  2s  . c o m*/
    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:ch.unibas.fittingwizard.presentation.fitting.FitResultPage.java

private void setupTable() {
    atomsTable.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<FitResultViewModel>() {
        @Override//from w  w w .j av  a  2  s  .  c o  m
        public void changed(ObservableValue<? extends FitResultViewModel> observableValue,
                FitResultViewModel fitResultViewModel, FitResultViewModel type) {
            setSelectedAtomType(type);
        }
    });

    atomTypeColumn.setCellValueFactory(new PropertyValueFactory<FitResultViewModel, String>("atomTypeName"));

    for (final String chargeType : ChargeTypes.all) {
        TableColumn<FitResultViewModel, FitResultViewModel.FitValue> column = new TableColumn<>(chargeType);

        column.setPrefWidth(80);
        column.setMinWidth(80);
        column.setCellValueFactory(
                new Callback<TableColumn.CellDataFeatures<FitResultViewModel, FitResultViewModel.FitValue>, ObservableValue<FitResultViewModel.FitValue>>() {
                    @Override
                    public ObservableValue<FitResultViewModel.FitValue> call(
                            TableColumn.CellDataFeatures<FitResultViewModel, FitResultViewModel.FitValue> data) {
                        return data.getValue().getChargeValueFor(chargeType);
                    }
                });
        column.setCellFactory(new ColoredCellCallback());

        atomsTable.getColumns().add(column);
    }
}

From source file:com.github.drbookings.ui.controller.MainController.java

private void addDateColumn() {
    final TableColumn<DateBean, LocalDate> col = new TableColumn<>("Date");
    col.setCellValueFactory(new PropertyValueFactory<>("date"));
    col.setCellFactory(column -> {
        return new TableCell<DateBean, LocalDate>() {
            @Override/*from ww  w.  j a v a2s  .  co  m*/
            protected void updateItem(final LocalDate item, final boolean empty) {
                super.updateItem(item, empty);
                if (item == null || empty) {
                    setText(null);
                    setStyle("");
                } else {
                    setText(DrBookingsApplication.DATE_FORMATTER.format(item));
                }
            }
        };
    });
    col.getStyleClass().addAll("center-left");
    tableView.getColumns().add(col);

}

From source file:com.github.drbookings.ui.controller.MainController.java

private void setTableColumns() {
    addDateColumn();//from   w w  w  . jav a 2s  . c om
    final int numberRooms = SettingsManager.getInstance().getNumberOfRooms();
    final String prefix = SettingsManager.getInstance().getRoomNamePrefix();
    for (int i = 1; i <= numberRooms; i++) {
        final TableColumn<DateBean, DateBean> col1 = new TableColumn<>(prefix + i);
        col1.setCellValueFactory(new PropertyValueFactory<>("self"));
        col1.setCellFactory(new StudioCellFactory("" + i));
        tableView.getColumns().add(col1);
    }
    addOccupancyRateColumn();
    addEarningsColumn();
}

From source file:com.github.drbookings.ui.controller.MainController.java

private void addEarningsColumn() {
    final TableColumn<DateBean, Number> col = new TableColumn<>("TotalEarnings");
    col.setCellValueFactory(new PropertyValueFactory<>("totalEarnings"));
    col.setCellFactory(column -> {
        return new TableCell<DateBean, Number>() {

            @Override/*www. j  a  v  a 2  s. c o m*/
            protected void updateItem(final Number item, final boolean empty) {
                super.updateItem(item, empty);
                if (item == null || empty) {
                    setText(null);
                } else {
                    setText(decimalFormat.format(item));
                }
            }
        };

    });
    col.getStyleClass().add("opace");
    tableView.getColumns().add(col);

}

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

private void setupTableWithChanges(TableView<Change> tv, Dataset tp) {
    tv.setEditable(true);// w  w  w.j  a 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: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. ja v a 2 s.  co  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:dtv.controller.FXMLMainController.java

public void init(ObservableList<DVBChannel> serviceData, TableView<DVBChannel> table,
        TableColumn<DVBChannel, Integer> idx, TableColumn<DVBChannel, String> name,
        TableColumn<DVBChannel, String> type, TableColumn<DVBChannel, String> ppr) {

    table.setEditable(true);//from w  ww . j  a  v  a  2s . com
    idx.setCellValueFactory(cellData -> cellData.getValue().idxProperty().asObject());
    name.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
    name.setEditable(true);
    type.setCellValueFactory(cellData -> cellData.getValue().typeProperty());
    // nid.setCellValueFactory(cellData -> cellData.getValue().nidProperty().asObject());
    ppr.setCellValueFactory(cellData -> cellData.getValue().pprProperty());
    // newCol.setCellValueFactory(cellData -> cellData.getValue().neewProperty());

    // Context menu
    table.setRowFactory(tableView -> {
        final TableRow<DVBChannel> row = new TableRow<>();
        final ContextMenu rowMenu = new ContextMenu();

        final MenuItem removeItem = new MenuItem("Delete");
        removeItem.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                final DVBChannel service = row.getItem();
                serviceData.removeAll(service);
            }
        });

        rowMenu.getItems().addAll(removeItem);
        row.contextMenuProperty().bind(Bindings.when(Bindings.isNotNull(row.itemProperty())).then(rowMenu)
                .otherwise((ContextMenu) null));

        return row;
    });

    ppr.setCellFactory(col -> {
        final TableCell<DVBChannel, String> cell = new TableCell<>();

        cell.textProperty().bind(cell.itemProperty());
        cell.itemProperty().addListener((obs, oldValue, newValue) -> {
            if (newValue != null) {
                final ContextMenu cellMenu = new ContextMenu();
                for (String pref : Utils.prefTab) {
                    final CheckMenuItem prefMenuItem = new CheckMenuItem(pref);

                    if (Utils.isPreferenceOn(cell.getText(), pref)) {
                        prefMenuItem.setSelected(true);
                    }

                    prefMenuItem.selectedProperty().addListener((obs1, old_val, new_val) -> {
                        final String new_ppr;
                        final DVBChannel service = (DVBChannel) cell.getTableRow().getItem();

                        if (new_val) {
                            new_ppr = Utils.add_ppr(cell.getText(), pref);
                        } else {
                            new_ppr = Utils.remove_ppr(cell.getText(), pref);
                        }

                        service.setPpr(new_ppr);
                        service.setModified(true);
                    });

                    cellMenu.getItems().add(prefMenuItem);
                    cell.setContextMenu(cellMenu);
                }
            } else {
                cell.setContextMenu(null);
            }
        });
        return cell;
    });

    // Editable service name
    name.setCellFactory(p -> new EditingCell());

    name.setOnEditCommit(t -> {

        final DVBChannel service = t.getTableView().getItems().get(t.getTablePosition().getRow());
        service.setName(t.getNewValue());
        service.setModified(true);
    });
}

From source file:com.github.vatbub.tictactoe.view.Main.java

private void initBoard() {
    guiAnimationQueue.submit(() -> {/*w ww  .  ja v a 2  s  .  com*/
        board = new Board(gameRows, gameCols);
        // set the ai level
        int sliderPos = (int) Math.round(aiLevelSlider.getValue() * 3.0 / 100.0);

        switch (sliderPos) {
        case 0:
            board.setAiLevel(AILevel.COMPLETELY_STUPID);
            break;
        case 1:
            board.setAiLevel(AILevel.SOMEWHAT_GOOD);
            break;
        case 2:
            board.setAiLevel(AILevel.GOOD);
            break;
        case 3:
            board.setAiLevel(AILevel.UNBEATABLE);
            break;
        }

        board.setGameEndCallback((winnerInfo) -> guiAnimationQueue.submit(() -> {
            // disconnect after ending the game
            if (board.getCurrentPlayer().getPlayerMode().equals(PlayerMode.internetHuman) || board
                    .getOpponent(board.getCurrentPlayer()).getPlayerMode().equals(PlayerMode.internetHuman)) {
                KryoGameConnections.resetConnections();
            }
            updateOpponentsTurnHBox(false, false);
            FOKLogger.info(Main.class.getName(), "The winner is: " + winnerInfo.winningPlayer.getName());
            if (winnerInfo.isTie()) {
                showTie();
            } else if (winnerInfo.winningPlayer.getPlayerMode().equals(PlayerMode.localHuman) && !board
                    .getOpponent(winnerInfo.winningPlayer).getPlayerMode().equals(PlayerMode.localHuman)) {
                showWinner(winnerInfo);
            } else if (winnerInfo.winningPlayer.getPlayerMode().equals(PlayerMode.localHuman) && board
                    .getOpponent(winnerInfo.winningPlayer).getPlayerMode().equals(PlayerMode.localHuman)) {
                showWinnerWithTwoHumanPlayers(winnerInfo);
            } else {
                showLooser(winnerInfo);
            }
        }));
        while (gameTable.getColumns().size() > 0) {
            gameTable.getColumns().remove(0);
        }

        for (int i = 0; i < gameCols; i++) {
            TableColumn<Row, String> column = new TableColumn<>(Integer.toString(i + 1));
            //noinspection Convert2Lambda
            int finalI = i;
            column.setCellValueFactory(p -> new SimpleStringProperty(p.getValue().getValues().get(finalI)));

            column.setCellFactory(new Callback<TableColumn<Row, String>, TableCell<Row, String>>() {
                @Override
                public TableCell<Row, String> call(TableColumn col) {
                    TableCell<Row, String> cell = new TableCell<Row, String>() {
                        // The updateItem method is what is called when setting the cell's text.  You can customize formatting here
                        @Override
                        protected void updateItem(String item, boolean empty) {
                            // calling super here is very important - don't skip this!
                            super.updateItem(item, empty);
                            if (item != null) {
                                setText(item);
                            }
                        }
                    };

                    cell.setOnMouseClicked(event -> {
                        if (board.getPlayerAt(cell.getIndex(), gameTable.getColumns().indexOf(col)) == null
                                && !isBlockedForInput()) {
                            setBlockedForInput(true);
                            boolean opponentIsInternetPlayer = board.getOpponent(board.getCurrentPlayer())
                                    .getPlayerMode().equals(PlayerMode.internetHuman);
                            board.doTurn(new Move(cell.getIndex(), gameTable.getColumns().indexOf(col)));
                            updateCurrentPlayerLabel(false, opponentIsInternetPlayer);
                            renderRows();
                        } else if (isBlockedForInput()) {
                            flashOpponentsTurnHBox();
                        }
                    });
                    return cell;
                }
            });

            column.setStyle("-fx-alignment: CENTER; -fx-padding: 0;");
            gameTable.getColumns().add(column);
        }

        renderRows();
    });
}

From source file:memoryaid.SetReminderController.java

@FXML
public void buildReminderTableData() throws SQLException {
    System.out.println("In builddata");

    DbConnection db = new DbConnection();
    Connection conn = db.connect();
    String SQL = "select RId,ReminderName,ReminderType,StartDate,EndDate,ReminderTime from reminders";
    ResultSet rs = conn.createStatement().executeQuery(SQL);

    TableColumn rIdCol = new TableColumn("RId");
    rIdCol.setCellValueFactory(new PropertyValueFactory<>("reminderId"));

    TableColumn reminderNameCol = new TableColumn("ReminderName");
    reminderNameCol.setCellValueFactory(new PropertyValueFactory<>("reminderName"));

    TableColumn reminderTypeCol = new TableColumn("ReminderType");
    reminderTypeCol.setCellValueFactory(new PropertyValueFactory<>("reminderType"));

    TableColumn startDateCol = new TableColumn("StartDate");
    startDateCol.setCellValueFactory(new PropertyValueFactory<>("startDate"));

    TableColumn endDateCol = new TableColumn("EndDate");
    endDateCol.setCellValueFactory(new PropertyValueFactory<>("endDate"));

    TableColumn reminderTimeCol = new TableColumn("ReminderTime");
    reminderTimeCol.setCellValueFactory(new PropertyValueFactory<>("reminderTime"));

    reminderTable.getColumns().add(rIdCol);
    reminderTable.getColumns().add(reminderNameCol);
    reminderTable.getColumns().add(reminderTypeCol);
    reminderTable.getColumns().add(startDateCol);
    reminderTable.getColumns().add(endDateCol);
    reminderTable.getColumns().add(reminderTimeCol);

    ObservableList<Object> data = FXCollections.observableArrayList();

    while (rs.next()) {
        String rId = String.valueOf(rs.getInt("RId"));

        data.add(new ReminderModel(rId, rs.getString("ReminderName"), rs.getString("ReminderType"),
                rs.getString("StartDate"), rs.getString("EndDate"), rs.getString("ReminderTime")));
    }//from   w  w w.j a va 2  s  . co  m
    rs.close();
    conn.close();

    Callback<TableColumn<ReminderModel, String>, TableCell<ReminderModel, String>> cellFactory = (
            TableColumn<ReminderModel, String> p) -> new EditingCell();

    //Code For Reminder Name update

    reminderNameCol.setCellValueFactory(new PropertyValueFactory<>("reminderName"));
    reminderNameCol.setCellFactory(cellFactory);
    reminderNameCol.setOnEditCommit(new EventHandler<CellEditEvent<ReminderModel, String>>() {

        @Override
        public void handle(CellEditEvent<ReminderModel, String> t) {
            ((ReminderModel) t.getTableView().getItems().get(t.getTablePosition().getRow()))
                    .setReminderName(t.getNewValue());

            System.out.println("*******" + t.getNewValue());
            ReminderModel selectedItem = (ReminderModel) reminderTable.getSelectionModel().getSelectedItem();
            System.out.println(selectedItem);
            String rIdToUpdate = selectedItem.getReminderId();
            Statement stmt = null;
            DbConnection db = new DbConnection();
            Connection conn = db.connect();

            try {
                stmt = conn.createStatement();

                String updateSql = "UPDATE Reminders set ReminderName = '" + t.getNewValue() + "'"
                        + "WHERE RId = '" + rIdToUpdate + "'";

                stmt.executeUpdate(updateSql);
            } catch (SQLException ex) {
                Logger.getLogger(SetReminderController.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

    });

    //For ReminderType Column Update

    reminderTypeCol.setCellValueFactory(new PropertyValueFactory<>("reminderType"));
    reminderTypeCol.setCellFactory(cellFactory);
    reminderTypeCol.setOnEditCommit(new EventHandler<CellEditEvent<ReminderModel, String>>() {

        @Override
        public void handle(CellEditEvent<ReminderModel, String> t) {
            ((ReminderModel) t.getTableView().getItems().get(t.getTablePosition().getRow()))
                    .setReminderType(t.getNewValue());

            System.out.println("*******" + t.getNewValue());
            ReminderModel selectedItem = (ReminderModel) reminderTable.getSelectionModel().getSelectedItem();
            System.out.println(selectedItem);
            String rIdToUpdate = selectedItem.getReminderId();
            Statement stmt = null;
            DbConnection db = new DbConnection();
            Connection conn = db.connect();

            try {
                stmt = conn.createStatement();

                String updateSql = "UPDATE Reminders set ReminderType = '" + t.getNewValue() + "'"
                        + "WHERE RId = '" + rIdToUpdate + "'";

                stmt.executeUpdate(updateSql);
            } catch (SQLException ex) {
                Logger.getLogger(SetReminderController.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

    });

    //For reminderTime Column Update

    reminderTimeCol.setCellValueFactory(new PropertyValueFactory<>("reminderTime"));
    reminderTimeCol.setCellFactory(cellFactory);
    reminderTimeCol.setOnEditCommit(new EventHandler<CellEditEvent<ReminderModel, String>>() {

        @Override
        public void handle(CellEditEvent<ReminderModel, String> t) {
            ((ReminderModel) t.getTableView().getItems().get(t.getTablePosition().getRow()))
                    .setReminderTime(t.getNewValue());

            System.out.println("*******" + t.getNewValue());
            ReminderModel selectedItem = (ReminderModel) reminderTable.getSelectionModel().getSelectedItem();
            System.out.println(selectedItem);
            String rIdToUpdate = selectedItem.getReminderId();
            Statement stmt = null;
            DbConnection db = new DbConnection();
            Connection conn = db.connect();

            try {
                stmt = conn.createStatement();

                String updateSql = "UPDATE Reminders set ReminderTime = '" + t.getNewValue() + "'"
                        + "WHERE RId = '" + rIdToUpdate + "'";

                stmt.executeUpdate(updateSql);
            } catch (SQLException ex) {
                Logger.getLogger(SetReminderController.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

    });

    reminderTable.setItems(data);

}