如何在JavaFX中的TableView中添加Rating

时间:2016-04-17 01:55:35

标签: java javafx tableview rating

在我的Java桌面应用程序中,我有一个TableView,其中我想要一个包含来自org.controlsfx.control.Rating的评级星的列。

@FXML
private TableView<Disciplina> tableFilter;
@FXML
private TableColumn<Disciplina, Rating> ratingColumn;
@FXML
private ObservableList<Disciplina> masterData = FXCollections.observableArrayList();

我在.setCellValueFactory(新的CallBack())中找到了一些东西,但我并不了解它是如何工作的。 那么如何在表格视图中添加这些评级星?

1 个答案:

答案 0 :(得分:0)

请勿使用cellValueFactory,请使用cellFactory在列中创建内容的直观表示。

TableView<RatingItem> tableView = new TableView<>(FXCollections.observableArrayList(
        new RatingItem(0),
        new RatingItem(2),
        new RatingItem(1),
        new RatingItem(4),
        new RatingItem(5)
));
tableView.setEditable(true);
TableColumn<RatingItem, Number> ratingColumn = new TableColumn<>("rating");
tableView.getColumns().add(ratingColumn);

// cellValueFactory gets value from item
ratingColumn.setCellValueFactory(cd -> cd.getValue().ratingProperty());

// cellFactory creates UI representation
ratingColumn.setCellFactory(table -> new TableCell<RatingItem, Number>() {

    private final Rating rating;

    private final ChangeListener<Number> ratingChangeListener;

    {
        rating = new Rating(5);

        // listener for changes in rating
        ratingChangeListener = (observable, oldValue, newValue) -> {
            TableColumn<?, Number> column = getTableColumn();

            // get the property used for this column (has to be WritableDoubleProperty)
            WritableDoubleValue value = (WritableDoubleValue) column.getCellValueFactory().call(new TableColumn.CellDataFeatures(getTableView(), column, getTableRow().getItem()));

            value.set(newValue.doubleValue());
        };
    }

    @Override
    protected void updateItem(Number item, boolean empty) {
        super.updateItem(item, empty);

        rating.ratingProperty().removeListener(ratingChangeListener);

        if (empty) {
            setGraphic(null);
        } else {
            rating.setRating(item.doubleValue());

            // only listen to changes done later through user interaction
            rating.ratingProperty().addListener(ratingChangeListener);
            setGraphic(rating);
        }
    }

});
public class RatingItem {

    private final DoubleProperty rating;

    public RatingItem(int rating) {
        this.rating = new SimpleDoubleProperty(rating);
    }

    public final double getRating() {
        return this.rating.get();
    }

    public final void setRating(double value) {
        this.rating.set(value);
    }

    public final DoubleProperty ratingProperty() {
        return this.rating;
    }

}