簡體   English   中英

JavaFX。 按條件更改 TreeItem 樣式

[英]JavaFx. Change TreeItem Style by condition

有 TreeView,其中的每個元素都實現了 Viewable 接口:

public interface Viewable {

    enum ViewStyle {

        NEW("-fx-background-color: b8faa7;"),
        NEW_PARENT("-fx-background-color: b8ebbb;"),
        LOCKED("-fx-background-color: adadad; "),
        HAS_NO_DATA("-fx-background-color: eb8d8d;");

        String style;

        ViewStyle(String style){
            this.style = style;
        }

        public String getStyle() {
            return style;
        }

    }

    ViewStyle getViewStyle();
    void setViewStyle(ViewStyle style);
    StringProperty styleProperty();

    String getTreeItemTitle();
    void setTreeItemTitle(String title);
    StringProperty titleProperty();

}

每個元素都有自己的 .styleProperty(),並從 ViewStyle.getStyle() 獲取值

每個 TreeCell.styleProperty() 的此屬性綁定:

treeView.setCellFactory(new Callback<TreeView<Viewable>, TreeCell<Viewable>>() {
            @Override
            public TreeCell<Viewable> call(TreeView<Viewable> param) {
                return new TreeCell<Viewable>() {
                    @Override
                    protected void updateItem(Viewable item, boolean empty) {
                        textProperty().unbind();
                        styleProperty().unbind();
                        if (empty || item == null) {
                            setGraphic(null);
                            textProperty().set(null);
                            styleProperty().set(null);
                            return;
                        }
                        if (item != null) {
                            styleProperty().bind(item.styleProperty());
                            textProperty().bind(item.titleProperty());
                        }
                        super.updateItem(item, empty);
                    }
                };
            }
        });

問題是樹單元在選擇中顯示得很丑陋。 即所選單元格的顏色不會改變。 只改變字母的顏色(按照默認主題),但不是很方便。 因此,可能需要附加 .css 文件。 同時,我不明白如何根據當前的 ViewStyle 更改單元格的樣式(默認和選中時)。

您可以簡單地將 css 屬性更改為僅用於未選定單元格的屬性( -fx-control-inner-background ):

enum ViewStyle {

    NEW("-fx-control-inner-background: b8faa7;"),
    NEW_PARENT("-fx-control-inner-background: b8ebbb;"),
    LOCKED("-fx-control-inner-background: adadad; "),
    HAS_NO_DATA("-fx-control-inner-background: eb8d8d;");

另請注意,您在updateItem方法的覆蓋版本中做了不應該做的updateItem :並不總是調用super.updateItem 這可能導致未正確分配已filled / empty偽類,並且TreeCellitem屬性不包含來自最新updateItem調用的項目。 你應該做這樣的事情:

@Override
protected void updateItem(Viewable item, boolean empty) {
    textProperty().unbind();
    styleProperty().unbind();
    if (empty || item == null) {
        setText(null);
        setStyle(null);
    } else {
        styleProperty().bind(item.styleProperty());
        textProperty().bind(item.titleProperty());
    }
    super.updateItem(item, empty);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM