To switch between two stylesheets in JavaFX, you can use the setUserAgentStylesheet
method of the Application
class to set the stylesheet for the application.
Here's an example of how you can do this:
import javafx.application.Application; import javafx.stage.Stage; public class Main extends Application { @Override public void start(Stage primaryStage) { // Set the first stylesheet Application.setUserAgentStylesheet(STYLESHEET_MODENA); // ... // Set the second stylesheet Application.setUserAgentStylesheet(STYLESHEET_CASPIAN); } }
This code will set the first stylesheet when the application starts, and then switch to the second stylesheet at a later point.
Note that the setUserAgentStylesheet
method only affects the styles of the JavaFX components, and does not affect the styles of HTML content displayed in a WebView. To switch between stylesheets for HTML content, you can use JavaScript to manipulate the link
elements in the HTML document.
Here's an example of how you can do this:
WebView webView = new WebView(); WebEngine webEngine = webView.getEngine(); // Switch to the first stylesheet webEngine.executeScript("document.getElementById('stylesheet1').disabled = false;"); webEngine.executeScript("document.getElementById('stylesheet2').disabled = true;"); // ... // Switch to the second stylesheet webEngine.executeScript("document.getElementById('stylesheet1').disabled = true;"); webEngine.executeScript("document.getElementById('stylesheet2').disabled = false;");
This code will disable the first stylesheet and enable the second stylesheet when switching to the second stylesheet.
Note that the executeScript
method requires the ScriptEngine
module to be enabled in your application. You can enable the ScriptEngine
module by adding the following line to your module-info.java
file:
requires javafx.web;