changing text color of a Menu control in JavaFX wi

2019-06-21 04:41发布

问题:

I want to change the text color of the Menu control in JavaFX. Currently, the background color of the whole Menu Bar is set to white and the default text color for displaying Menu-s is also white, so I cannot see the actual control, therefore I want to set the text color of the Menu ("File") to black. How do I do that?

Here's the FXML portion:

<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml">
  <children>
    <MenuBar id="modBar" layoutX="176.0" layoutY="122.0" styleClass="modBar">
      <menus>
        <Menu id="modItem" mnemonicParsing="false" styleClass="modItem" text="File" />
      </menus>
      <stylesheets>
        <URL value="test.css" />
      </stylesheets>
    </MenuBar>
  </children>
</AnchorPane>

Here's the CSS part:

.modBar
{
    -fx-background-color: white;
}
.modItem
{
    -fx-color: black;
}

This doesn't work ("File" still remains white). What am I doing wrong? Also, another thing is that I cannot seem to apply anything with CSS to .modItem - it sort-of works in Scene Builder, but disappears once previewed (also the "Stylesheets" selector is missing on all Menu-s in SB).

回答1:

OK, think I have found the answer. What I did was extract caspian.css out of jfxrt.jar (the default CSS theme JavaFX uses) and inspect everything related to Menu-s:

.menu .label
{
    -fx-text-fill: black;
}

This will influence all Menu controls.


By the way, there was a particular build of Scene Builder that might come of interest - b42, this had an additional CSS menu that exposed internal styles of controls/elements, so customizing turns into a straightforward operation (without the need of prior manual extraction of the applied style).



回答2:

I'm not sure, but you set the id attribute - doesn't that mean you can only access them via #modBar or #modItem ???

I'm also quite new to JFX2 (about a month) and unfortunatelly in all my years as a Java developer I never needed to play around with css, so it's just an assumption.