Search code examples
user-interfacejavafxfxmlfont-size

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.

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.)