如何修改ControlsFX Notification背景:Java/CSS实现白背景改绿背景
Hey there! I’ve dealt with this exact issue before when customizing ControlsFX’s Notification component. Since it doesn’t expose a getStylesheet() method, we’ve got two solid ways to change that white background to green—let’s break them down:
This is quick and straightforward if you only need to customize a single Notification instance:
- First, create your Notification as usual, then grab its underlying
Popupobject usinggetPopup() - Access the root content node of the Popup (it’s the first element in the content list)
- Apply the background color style directly to this node—you can also adjust text color to ensure readability against the green background
Here’s the code example:
// Create your Notification Notification notification = Notification.create() .title("Custom Notification") .text("This has a green background!") .show(); // Wait for the popup to be shown before modifying styles (avoids null issues) notification.getPopup().setOnShown(event -> { Node rootNode = notification.getPopup().getContent().get(0); // Set green background and white text rootNode.setStyle("-fx-background-color: #2ecc71; -fx-text-fill: white;"); // If you need to target the inner label specifically: rootNode.lookup(".label").setStyle("-fx-text-fill: white;"); });
If you want all Notification instances in your app to have the green background, use a global CSS file. ControlsFX’s Notification uses the .notification CSS class for its root container, so we can target that:
First, create a CSS file (e.g., notification-styles.css) with these rules:
/* Target the Notification's root container */ .notification { -fx-background-color: #2ecc71; /* A nice green shade */ -fx-border-color: #27ae60; /* Optional: add a darker green border */ -fx-border-width: 2px; } /* Ensure text is readable on green background */ .notification .label { -fx-text-fill: white; } /* Customize the title label if needed */ .notification .title-label { -fx-text-fill: white; -fx-font-weight: bold; }
Then, load this CSS file into your JavaFX application or scene:
// Option 1: Load for the entire application Application.setUserAgentStylesheet(getClass().getResource("/notification-styles.css").toExternalForm()); // Option 2: Load for a specific Scene only Scene scene = new Scene(new BorderPane()); scene.getStylesheets().add(getClass().getResource("/notification-styles.css").toExternalForm());
Just make sure your CSS file is placed correctly in your project’s resources folder so the getResource() call can find it.
内容的提问来源于stack exchange,提问作者code kiler

