【问题标题】:In JavaFX, how can I switch skins using CSS?在 JavaFX 中,如何使用 CSS 切换皮肤?
【发布时间】:2015-02-05 07:41:11
【问题描述】:

在 JavaFX 中通过 CSS 定义 Skin 的正确位置是什么?假设我有一个非常简单的自定义控件...

public class ActionLink extends Control {
    private final StringProperty text = new SimpleStringProperty();
    public final StringProperty textProperty() {return text;}
    public final String getText() {return text.get();}
    public final void setText(String text) {this.text.set(text);}
}

我知道我可以在控件中指定默认皮肤。假设我有一个ActionLinkSkin...

@Override
protected Skin<?> createDefaultSkin() {
    return new ActionLinkSkin(this);
}

如果我不使用createDefaultSkin(),我会看到SEVERE 警告,表明找不到皮肤:

The -fx-skin property has not been defined in CSS for ActionLink@59ebabd \
  and createDefaultSkin() returned null.

首先,我不确定控件的 CSS 属于哪里。我应该为控件使用样式表action-link.css,还是应该为皮肤使用样式表action-link-skin.css?对我来说,外观和 CSS 似乎会相互依赖,但使用样式表作为控件似乎更受欢迎。

第二个,也是我的主要问题,我不知道在哪里定义 -fx-skin 所以它会被正确发现。

现在,假设我的 CSS 设置正确,如果我想包含一个备用皮肤 ActionLinkButtonSkin 怎么办?有没有办法可以设置它,以便父组件可以通过 CSS 选择任一皮肤?例如:

.action-link {
    -fx-skin: "ActionLinkSkin";
}

...或:

.action-link {
    -fx-skin: "ActionLinkButtonSkin";
}

【问题讨论】:

    标签: javafx-8 javafx-css


    【解决方案1】:

    我在这里遇到的问题是我没有将action-link 样式添加到我的控件中。这是我简单的ActionLink控件的完整版本:

    public class ActionLink extends Control {
        static {
            // Stylesheets is a custom class that resides alongside my CSS files
            // and returns properly externalized locations in a convention based
            // manner.
            StyleManager.getInstance().addUserAgentStylesheet(
                Stylesheets.byConvention(ActionLink.class)
            );
        }
    
        private final StringProperty text = new SimpleStringProperty();
        public final StringProperty textProperty() {return text;}
        public final String getText() {return text.get();}
        public final void setText(String text) {this.text.set(text);}
    
        public ActionLink() {
            getStyleClass().setAll("action-link");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      相关资源
      最近更新 更多