Evan
Evan

Reputation: 714

How to set global CSS in JavaFX 9+ application?

There're couple of questions alerady on SO, however since JPMS support none of the answers are valid.

method 1: (JavaFX - Set default CSS stylesheet for the whole Application)

Application.setUserAgentStylesheet(Application.STYLESHEET_MODENA);
StyleManager.getInstance().addUserAgentStylesheet(getClass().getResource("/style.css").toString());

Doesn't work because StyleManager became the part of private API and JavaFX doesn't export it.

method 2: (https://stackoverflow.com/a/51003008/7421700)

@import "com/sun/javafx/scene/control/skin/modena/modena.css";
/* rest of CSS code */

Doesn't work because modena.css became the part of private API and JavaFX doesn't export it.

method 3: set CSS to the top parent node (https://stackoverflow.com/a/28880421/7421700)

Doesn't work because CSS will not be applied to modal windows.

Upvotes: 11

Views: 1508

Answers (1)

Dave Jarvis
Dave Jarvis

Reputation: 31171

Apply the stylesheet to the scene by calling Scene's getStylesheets() method. This is how my application changes the entire application look and feel at runtime:

 private void applyStylesheets(
    final Scene scene, final String internal, final File external ) {
    final var stylesheets = scene.getStylesheets();
    stylesheets.clear();
    stylesheets.add( STYLESHEET_APPLICATION_BASE );
    stylesheets.add( STYLESHEET_MARKDOWN );
    stylesheets.add( getStylesheet( toFilename( internal ) ) );

    try {
      if( external != null && external.canRead() && !external.isDirectory() ) {
        stylesheets.add( external.toURI().toURL().toString() );
        mFileWatchService.register( external );
      }
    } catch( final Exception ex ) {
      clue( ex );
    }
  }

The code is doing the following:

  1. Obtain a reference to the current stylesheets from the Scene.
  2. Clear out the list of existing stylesheets.
  3. Add the base stylesheet, stylesheet for the rich text editor, then the user-selected stylesheet.
  4. Add an externally sourced stylesheet, with additional overrides.
  5. Optionally (for you), add a watch on the externally sourced stylesheet so that if the file is changed, the UI is updated immediately.

See the complete code snippet for context and further details.

Upvotes: 1

Related Questions