Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change font of TextField without affecting context menu

Setting a custom font style on a TextField in JavaFX will also affect its default context menu, I noticed. What can I do to change the font of the user input, but keep the menu items in the context menu as they would show up normally?

.custom-text-field {
  -fx-alignment: center;
  -fx-font-size: 2.5em;
  -fx-font-weight: bold;
  -fx-font-family: monospaced;
}

I’m searching for a solution in CSS style, I do not want to alter the font in Java code.

The documentation of the TextField component has been of little use.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Neither has checking the default CSS style in caspian.css helped me much, unfortunately.

>Solution :

The reason this happens is that the context menu is a (direct) descendant of its control (see the documentation for ContextMenu), and the default value for a font is inherit, so by default the context menu will inherit the font from the control to which it is attached.

One way is to specifically reset the style for the context menu:

.custom-text-field {
  -fx-alignment: center;
  -fx-font-size: 2.5em;
  -fx-font-weight: bold;
  -fx-font-family: monospaced;
}
.custom-text-field > .context-menu * {
    -fx-font: null;
}

If you want to "globally" enforce the rule "don’t inherit context menu’s fonts from their control", the following more general CSS rule will do this:

.context-menu {
    -fx-font: null;
}

(This removes the inherit value for the context menu’s font.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading