繁体   English   中英

如何在JavaFX中的TableView中添加评分

[英]How to add a Rating inside a TableView in JavaFX

在我的Java桌面应用程序中,我有一个TableView,其中我想有一列包含org.controlsfx.control.Rating中的Rating stars的列。

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

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

不要使用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;
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM