javafx root -fx-font-size and em sizing

2019-07-04 00:55发布

问题:

I'm trying to resize my layout elements using a root font-size and 'em' values. It looks like whenever I "touch" the -fx-font-size attribute, the root's font size is being reset to the base value (1em = 12px).

For the simple fxml:

<BorderPane fx:id="mainStack" prefWidth="600" prefHeight="400" stylesheets="/style.css" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
   <left>
      <VBox fx:id="leftPane">
         <Button text="btn1"></Button>
         <Button text="btn2" styleClass="textBigger"></Button>
         <Button text="btn3"></Button>
      </VBox>
   </left>
</BorderPane>

and css like:

.root {
    -fx-font-size: 10px;
    -fx-background-color: Lime;
}
#leftPane {
    /*-fx-font-size: 10px;*/
    -fx-background-color: Green;
    -fx-pref-width: 40em;
    -fx-spacing: 1em;
}
.button {
    -fx-background-color: Yellow;
    -fx-pref-height: 5em;
    -fx-pref-width: 20em;
}

#leftPane .textBigger {
    -fx-font-size: 1.5em;
}

sample 1 is for root -fx-font-size = 10 sample 2 is for root -fx-font-size = 20

Button 1 and 3 as well as overall layout are as expectedd, but on button 2 pref-width and pref-height are being seized as multiplication of 12 instead of 10 or 20. So button 2 size is always 240x60.

Am I doing something wrong here or maybe someone knows a solution how to prevent root -fx-font-size "reset".

Bartek

回答1:

Yes, it is the BUG by the the javafx.scene.CssStyleHelper, look at the the code-line 1388:

boolean isFontProperty = "-fx-font".equals(property) || "-fx-font-size".equals(property);

then 1392:

boolean isRelative = ParsedValueImpl.containsFontRelativeSize(resolved, isFontProperty);

and 1444:

// did we get a fontValue from the preceding block?
// if not, get it from our cacheEntry or choose the default
if (fontForFontRelativeSizes == null) {
    if (fontFromCacheEntry != null && fontFromCacheEntry.isRelative() == false) {
        fontForFontRelativeSizes = (Font)fontFromCacheEntry.getValue();
    } else {
        fontForFontRelativeSizes = Font.getDefault();
    }
}

It must be fixed under the https://bugreport.java.com/bugreport/submit_start.do, ID: 9055560.

As a workaround - to define -fx-font-size: XXXem; not in a .control-class, but deeply, for example in the .text-class, in your case:

#leftPane .textBigger .text {
    -fx-font-size: 1.5em;
}

Then the -fx-font-size: 2em; belongs only to the .text-class and doesn’t influence on the higher .textBigger-class.