CheckBoxTableCell不使用ObjectProperty <boolean>

时间:2018-03-07 14:32:06

标签: java javafx

我扩展了SimpleObjectProperty<T>以创建自定义的延迟加载实现(see here),LazyLoadingObjectProperty<T>

要将此泛型实现用于布尔属性,我使用LazyLoadingObjectProperty<Boolean>

在我的表中,我想将布尔属性渲染为CheckBox

尽管如此, CheckBoxTableCell似乎仅适用于BooleanProperty,但不适用于ObjectProperty<Boolean>

为什么会这样,我该如何解决?

以下是一些代码:

public class ExampleTable extends Application {

    private static final int NUM_ELEMENTS = 5000;

    private final TableView<ExampleBean> table = new TableView<>();

    private final ObservableList<ExampleBean> data = FXCollections.observableArrayList();

    public static void main(final String[] args) {
        launch(args);
    }

    @Override
    public void start(final Stage stage) {
        final Scene scene = new Scene(new Group());
        stage.setTitle("Table View Sample");
        stage.setWidth(300);
        stage.setHeight(500);

        final TableColumn<ExampleBean, Boolean> c1 = new TableColumn<>("A");
        c1.setCellValueFactory(new PropertyValueFactory<ExampleBean, Boolean>("p1"));
        c1.setCellFactory(CheckBoxTableCell.forTableColumn(c1));
        c1.setEditable(true);
        c1.setPrefWidth(100);

        final TableColumn<ExampleBean, String> c2 = new TableColumn<>("B");
        c2.setCellValueFactory(new PropertyValueFactory<ExampleBean, String>("p2"));
        c2.setCellFactory(TextFieldTableCell.forTableColumn());
        c2.setEditable(true);
        c2.setPrefWidth(100);


        for (int i = 0; i < NUM_ELEMENTS; i++) {
            data.add(new ExampleBean());
        }

        final ScrollPane sp = new ScrollPane();
        sp.setContent(table);
        sp.setMaxHeight(Double.POSITIVE_INFINITY);
        sp.setMaxWidth(Double.POSITIVE_INFINITY);
        sp.setFitToHeight(true);
        sp.setFitToWidth(true);

        table.setEditable(true);
        table.setItems(data);
        // table.setMaxHeight(Double.POSITIVE_INFINITY);
        // table.setMaxWidth(Double.POSITIVE_INFINITY);
        table.getColumns().addAll(c1, c2);

        final ContextMenu cm = new ContextMenu();
        cm.getItems().add(new MenuItem("bu"));
        table.setContextMenu(cm);

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        VBox.setVgrow(sp, Priority.ALWAYS);
        vbox.getChildren().addAll(sp);

        scene.setRoot(vbox);

        stage.setScene(scene);
        stage.show();
    }
}

public class ExampleBean {

    private ObjectProperty<Boolean> p1;

    private ObjectProperty<String> p2;


    public ExampleBean() {
        p1 = new SimpleObjectProperty(true);
        p1.addListener((o, ov, nv) -> {
            System.err.println("Value changed " + ov + " -> " + nv);
        });

        p2 = new SimpleObjectProperty(Integer.toString(new Random().nextInt()));
        p2.addListener((o, ov, nv) -> {
            System.err.println("Value changed " + ov + " -> " + nv);
        });
    }

    public final ObjectProperty<Boolean> p1Property() {
        return this.p1;
    }

    public final ObjectProperty<String> p2Property() {
        return this.p2;
    }
}

请注意,该属性已使用Boolean.TRUE初始化,并且未检查CheckBoxCell。

此问题未使用/需要:

public abstract class LazyLoadingObjectProperty<T> extends SimpleObjectProperty<T> {

    public LazyLoadingObjectProperty() {
        super();

    }

    public LazyLoadingObjectProperty(final Object bean, final String name, final T initialValue) {
        super(bean, name, initialValue);

    }

    public LazyLoadingObjectProperty(final Object bean, final String name) {
        super(bean, name);

    }

    public LazyLoadingObjectProperty(final T initialValue) {
        super(initialValue);

    }

    private boolean loaded = false;

    private final ChangeListener<T> valueChangeListener = (o, ov, nv) -> {
        valueExternallyUpdated(nv);
    };

    /**
     * Is called after the background task's finished (success or failure). Override
     * if needed. E.g. to bind the value afterwards.
     */
    protected void afterLoaded() {
        addListener(valueChangeListener);

    }

    /**
     * Returns a {@link Task} that will calculate this Property's value in the
     * background.
     *
     * @return a {@link Task} that will calculate this Property's value in the
     *         background.
     */
    protected abstract Task<T> createTask();

    protected T getFailedValue(final Throwable t) {
        return null;
    }

    @Override
    public T getValue() {
        if (!loaded) {
            startLoadingService();
        }
        return super.getValue();
    }

    public boolean isLoaded() {
        return loaded;
    }

    public void setLoaded(final boolean loaded) {



        // the loaded property has been reset manually. Remove change listener
        if (this.loaded && !loaded) {
            removeListener(valueChangeListener);
        }

        this.loaded = loaded;
    }

    @Override
    public void setValue(final T v) {
        super.setValue(v);
    }

    /**
     * Starts the {@link Task} that will calculate this Property's value in the
     * background.
     */
    protected void startLoadingService() {
        setLoaded(true);
        final Task<T> s = LazyLoadingObjectProperty.this.createTask();

        LazyLoadingThreads.getExecutorService().submit(s);

        s.setOnFailed(e -> {
            setValue(getFailedValue(e.getSource().getException()));
            afterLoaded();
        });

        s.setOnSucceeded(e -> {
            setValue(s.getValue());
            afterLoaded();
        });

    }

    /**
     * Override this callback method to handle external value-change-events
     * (not-lazily-loaded). This callback is only called, if the value is updated
     * manually, i.e., not via the lazy-loading mechanism.
     *
     * @param nv
     *            the new value
     */
    protected void valueExternallyUpdated(final T nv) {
        // override if needed

    }

}

找到mwe here

1 个答案:

答案 0 :(得分:2)

绝对是一个错误,至少在doc中,但也在实现中:选中的checkBox和索引中的observableValue之间的自动bidi绑定 - 如果可能 - 是 设计意图。即使可能,实施也无法满足该要求。

快速入侵是修复错误的自定义子类,类似于(未经过正式测试,请注意!):

public static class FixedCheckBoxTableCell<S, T> extends CheckBoxTableCell<S, T> {

    @Override
    public void updateItem(T item, boolean empty) {
        checkCallback();
        super.updateItem(item, empty);
    }

    private void checkCallback() {
        if (getSelectedStateCallback() != null) return;
        ObservableValue<Boolean> observable = 
                (ObservableValue<Boolean>) getTableColumn().getCellObservableValue(getIndex());
        // handled by super
        if (observable instanceof BooleanProperty) return;
        // can't bidi-bind anyway
        if (!(observable instanceof Property)) return;
        // getting here if we have a ObjectProperty<Boolean>, that's not handled by super
        setSelectedStateCallback(index -> {
            ObjectProperty<Boolean> p = (ObjectProperty<Boolean>) getTableColumn().getCellObservableValue(index);
            return BooleanProperty.booleanProperty(p);
        });
    }


}