Adding CSS stylesheets on-the-fly in JavaFX

I am looking to incorporate a CSS file from the filesystem into my application. The goal is to allow users to dynamically add JavaFX CSS files that can be created by anyone and stored anywhere on their system.
I attempted a test scenario to see if adding CSS files dynamically would work:

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Label label = new Label("Hello");
        Scene scene = new Scene(label);

        //file path set by user using file chooser
        File file = new File("C:/test.css");
        scene.getStylesheets().add(file.getAbsolutePath());

        primaryStage.setTitle("Title");
        primaryStage.setScene(scene);
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

However, I encountered an error every time:

WARNING: com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged Resource "C:\test.css" not found. 

What steps should I take to resolve this issue?

Answer №1

To include CSS in the same package, you can simply add the following code:

scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());

Answer №2

Your issue lies in the absence of a URL usage. To resolve this, refer to this link for comprehensive documentation on loading CSS files and the CSS reference.

If you possess the URL as a String, you can dynamically apply the CSS with an external file using the following approach:

private boolean isANext = true;

public void start(Stage primaryStage) throws Exception {
    Button button = new Button("Change CSS");
    VBox vbox = new VBox(10);
    vbox.setAlignment(Pos.CENTER);
    vbox.getChildren().add(button);
    scene = new Scene(vbox, 200, 200);

    button.setOnAction(ev -> {
        // Demonstration of alternating between two stylesheets.
        String css = isANext ? "file:///C:/temp/a.css" : "file:///C:/temp/b.css";
        isANext = !isANext;
        System.out.println("Loading CSS at URL " + css);

        scene.getStylesheets().clear();
        scene.getStylesheets().add(css);
    });

    primaryStage.setTitle("Title");
    primaryStage.setScene(scene);
    primaryStage.show();
}

The contents of a.css:

.button {    
    -fx-text-fill: white;
    -fx-background-color: red;
}

And the contents of b.css:

.button {    
    -fx-text-fill: white;
    -fx-background-color: black;
}

Answer №3

The URL can be obtained using the java.io.File class.

File file = new File("style.css");
URL url = file.toURI().toURL();
scene.getStylesheets().add(url.toExternalForm());

Alternatively, you can achieve this in a more concise way:

scene.getStylesheets().add((new File("style.css")).toURI().toURL().toExternalForm());

Answer №4

An error occurs when the specified string "C:/test.css" is not recognized as a URI resource. To resolve this issue, you need to convert the string into a valid URI resource.

Starting from Java 7, you can achieve this using the following code:

String uri = Paths.get("C:/test.css").toUri().toString();
scene.getStylesheets().add(uri);

Answer №5

customize.setBrowserStyles("Assets/StyleSheets/Styless.css");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing Selenium Chrome driver to pinpoint a specific attribute associated with a label

Can anyone help me with targeting and clicking on the specific regOption bar to proceed with the test? I attempted to instruct the driver to use the following XPath directly. driver.findElement(By.xpath("//*[@id='regOptions']/div[2]/div[3]/p[1] ...

Tips on positioning only one list item on your Bootstrap navbar to the right

I am currently learning to code with HTML and am attempting to create a navigation bar with some list items on the right side and some on the left. Although I'm using Bootstrap, I am unable to figure out how to move only the 'contact' item t ...

The scroll() function in jQuery does not bubble up

Recently, I encountered an issue with a Wordpress plugin that displays popups on scroll. The code I currently have is as follows: jQuery(window).scroll(function(){ //display popup }); The problem arises with a particular website that has specific CSS ...

Highslide's Page Z-Index Elevation

Hey there, I'm currently facing an issue with the z-index positioning of an in-page gallery on my website. I attempted to use the hs.zIndexCounter attribute but unfortunately, it didn't solve the problem. Just so you know, my navigation bar has ...

Using inline styles can cause Content Security Policy (CSP) violations in applications

I have been diligently working on an application for quite some time using create-react-app. Recently, I decided to update to the latest version of React only to find out that a new Content Security Policy (CSP) has been implemented. To my dismay, upon tr ...

Mobile device causing elements to resize unevenly

On my simple webpage, I have a combination of text and a table. Check out the HTML below: <body> <div id='stat'> <p class='subheading'>Stat of the Week: Average Final Standings</p> <p class='text&apo ...

Constantly centered div

I'm dealing with a situation like this: .center_position_div{ width:100%; background-color:green; display: flex; flex-wrap: wrap; } .show_running_exam { width: 22%; background-color:aliceblue; margin-left: 1%; margi ...

Why is my CSS media query failing to increase font size?

I can't seem to get the "media query" function to work properly. I've tried multiple times and searched for a solution without any luck. Below is the code snippet where I'm attempting to increase the font size from 44px to 70px on small devi ...

How can I make an image fill the container with CSS zoom effect

My website features a full viewport image as the background beneath the Nav Bar. I am looking to achieve a specific effect on mobile where the image is zoomed in and centered without distortion, allowing some of it to still be visible as a background. The ...

The el-dialog is functioning properly, however, I am looking to add CSS that will animate it to open

I've set up a dialog to open on button click, and it's functioning correctly. My goal is to have the dialog open from the bottom with a height of 300px, show the contents inside it, and then hide when I click outside or inside any element. Here ...

End the div element upon completion of the Vimeo video

I am in need of a website that includes an intro video displayed as a full-width div over the background content. To achieve this, I created a Div containing an iframe video from Vimeo along with a button to skip the intro (which closes the div upon clicki ...

The mysterious case of the vanishing close button on Curator.io's mobile

Currently, I am using curator.io aggregator to showcase my Instagram feed on the website. An issue arises when switching to mobile view as the close button (class="crt-close") disappears. You can see an example of this here: To replicate the pr ...

The modal box should adjust its height to perfectly accommodate the content within

I'm in the process of developing a straightforward modal (popup) window, using as few lines of code as possible... just the basics. The modal has a maximum width of 650px and its height adjusts to fit the content. In case the content exceeds the avai ...

Can the typical drag and drop cursors be ignored in an HTML drag operation?

I've been working with the HTML drag and drop API to allow users to resize columns in a table. However, I've noticed that when a user starts dragging a column, the cursor changes to one of the default drag and drop effects (such as move or none). ...

Tips for creating a responsive background image that adjusts after resizing the window to a certain width

Is there a way to create a responsive background-image that adjusts when the window is resized to a specific width, similar to the main image on ? ...

Having trouble getting HTML to render properly in React JS on localhost using Apache server

For the past week, I've been working on resolving an issue. I started by creating a React Application using: npm create react-app After that, I attempted to build it with: npm run build Everything seemed to go smoothly. I generated a build folder ...

I'm curious if it's possible to modify a webpage loaded by HtmlUnit prior to the execution of any javascript code

To begin, I want to elaborate on the reasoning behind my question. My current task involves testing a complex web page using Selenium + HtmlUnit, which triggers various JavaScript scripts. This issue is likely a common one. One specific problem I encount ...

Make sure to employ Bootstrap's justify-content-between and stack-to-horizontal col correctly

I am currently working on a responsive form that contains 1 label, 1 input field, and 5 buttons. Both the buttons and the input field are located under col-8. The positioning I aim for the buttons is as follows: They should start below and align with ...

Div positioned absolutely beneath the footer

I'm facing an issue where the footer field I add under a div with an absolute value escapes on both mobile and desktop. Additionally, the iframe does not have full height. Any suggestions on what I should do? All the specifics are provided in the att ...

Minimum width of Angular Material's mat-menu

I am looking to create a compact Material mat-menu using Angular 15. Below is the code I have: <mat-menu #flagMenu="matMenu"> <button mat-menu-item> <img src="assets/flags/en.png" class="flag"/> ...