Adding a new style class

To make a new style class, we need to perform the following actions:

  1. Add StyleableProperty to the property we want to control through CSS.
  2. Configure CssMetaData for this property.
  3. Expose this metadata through the getCssMetaData() method.

The  CssMetaData describes our new styleable property:

  • Sets its name, "-fx-hh-color", which will be used in CSS.
  • Sets the converter, which will convert strings from CSS into required Java objects. We will use a helper class, PaintConverter, from the javafx.css package. There is a whole range of such converters there.
  • Allows read-only mode through the isSettable abstract method. In our example the only thing which may block us is binding, so we will check if the property is bound in this method.
  • Links CSS engine to the property we plan to use through the getStyleableProperty method.

Take a look at the following code snippet:

private static final CssMetaData<ClockControl, Paint> HH_COLOR_METADATA = 
new CssMetaData("-fx-hh-color", PaintConverter.getInstance()) {
@Override
public boolean isSettable(Styleable styleable) {
return !((ClockControl)

return !((ClockControl) styleable).
hourHand.fillProperty().isBound();
}

@Override
public StyleableProperty getStyleableProperty(Styleable styleable) {
return ((ClockControl)

return ((ClockControl) styleable).
hourHandColorStyleableProperty;
};

To make a styleable property, we'll again use a helper class, javafx.css.SimpleStyleableObjectProperty. It will do all the plumbing for us, the only thing left to code is updating the color:

private SimpleStyleableObjectProperty<Paint> hourHandColorStyleableProperty = 
new SimpleStyleableObjectProperty(HH_COLOR_METADATA) {
@Override
protected void invalidated() {
hourHand.setFill((Paint) get());
}
};

Now we can inform JavaFX about our new styleable through getCssMetaData():

    private static final List<CssMetaData<? extends Styleable, ?>> cssMetaDataList;
static {
List<CssMetaData<? extends Styleable, ?>> temp =
new ArrayList<>(BorderPane.getClassCssMetaData());
temp.add(HH_COLOR_METADATA);
cssMetaDataList = Collections.unmodifiableList(temp);
}

@Override
public List<CssMetaData<? extends Styleable, ?>> getCssMetaData() {
return cssMetaDataList;}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.38.121