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

Develop a CSS layout for the specified design

Aiming to achieve a unique layout using dynamic html strings. The challenge arises when transitioning to the second page as the layout does not adjust upward and images cannot be added to the first page. Attempting to implement the following sample code ...

HTML: Base64 image not displaying properly due to incorrect height specification

I have a straightforward base64 image that I am having trouble with. The issue is that only the upper half of the image is displaying. If I try to adjust the height using the "style" attribute in the img tag: style="height: 300px;" it shows correctly. Ho ...

"Exploring the world of JSON with Android and Java

Just delving into the world of JSON and experimenting with the FLOT graph for displaying graphs via WebView. Struggling with JSON parsing to represent my data as JavaScript expects. Despite hours of tinkering, I can't seem to format my JSON output to ...

Creating a loader for a specific component in Angular based on the view

Creating a loader for each component view is crucial when loading data from an API. Here is the current structure of my components within my <app-main></app-main>: <app-banner></app-banner> <app-data></app-data> <app ...

The edge of the 'parent' element is obscured by the :after element

I am trying to create a transparent outlined button with a shadow in the shape of the button. However, I am facing an issue where the border of the button appears behind the :after element. You can see the problem below. Adding overflow: hidden to the tog ...

photos arranged in rows rather than a single row

Looking for help with arranging the remaining photos in the second row? Check out this example image link. I'm struggling to organize a row of overflow images within the "small-img-row" division. This row is located under the main image in col-2. H ...

Toggle JavaScript Query Display

Welcome to my HTML test website where I am testing show/hide JavaScript functionality. Upon loading the page, you may notice that everything is hidden until a button is clicked. <html> <head><title>Test</title> <scr ...

Potential image positioned to the left of a detailed description

A Meteor client template helper contains an array of objects {image: url, label: description}. The URL can either point to a valid image file in the public directory or be the string 'non'. The description can range from a few words to several ...

Placing a pseudoelement amidst the track and thumb of a range input type

I'm trying to position a pseudo element with a specific z index that is lower than the thumb of an input type range but higher than its track. This is what I have so far: HTML: <div class="range"> <input type="range" name="" class="progre ...

To access the link, simply click once if there is no child menu. However, if there is a child menu attached, be sure to click

I am working on a mobile menu that is designed to slide out when clicked. Currently, the parent pages are displayed by default. I want to implement functionality where if a parent page has child pages, clicking on it will slide down the sub menu. If click ...

Leverage the power of Angular by configuring a custom webpack setup to

Implementing the CSS modules concept in my Angular app has been a challenge due to conflicts with existing frontend CSS. My project utilizes SCSS, and I am looking for a way for webpack to modularize the CSS generated from SCSS during the final build step. ...

java.lang.RuntimeException: Activity ComponentInfo in Android could not be launched

Currently facing an issue while attempting to parse a JSON object Value on this website. I keep receiving a runtime error that states: Unable to start activity componentinfo: Illegal character in URL. Here is the code snippet: Attempting to address the &a ...

What is the best way to retrieve an object using callback data with jQuery?

Using jquery with a servlet to fetch data from a database. The callback function provides raw information from the database. How can I append these values to select options in jsp? Retrive_country servlet code: String sql1 = "SELECT * FROM state WHERE co ...

Positioning children within a div element

Howdy! I have a neat little setup with two divs stacked on top of each other, each containing child elements. My goal is to hide the first div and have the second div seamlessly take its place while keeping the child elements in their original position. C ...

Make the background image draggable while maintaining its size with background-size:cover

I'm working on a fixed div with an image as the background, set up like this: <div style=' width:230px; height:230px; background-repeat: no-repeat; background-image:url(img/myimage.jpeg) background-size: cover;'&g ...

Turning HTML elements 90 degrees for vertical printing without the need for a landscape class

My current project involves creating a template for generating PDF files with CSS. I've set up different paper sizes and orientations using @page and media queries in my CSS code. You can check out a snippet of the CSS here. One challenge I'm fa ...

Ways to reduce lag while executing a for loop

How can I optimize my prime number generation process to avoid lagging? For example, is there a way to instantly display the results when generating primes up to 1000? HTML: <!DOCTYPE html> <html> <meta name="viewport" content="width=dev ...

The font size appears significantly smaller than expected when using wkhtmltoimage to render

I am trying to convert text into an image, with a static layout and size while adjusting the font size based on the amount of text. I prefer using wkhtmltoimage 0.12.5 as it offers various CSS styling options. Currently, I am working on a Mac. Below is a ...

Ways to position a child element at the center of its parent container?

Hey there, is there a way I can achieve this specific layout without relying on position: absolute? Flexbox would be the preferred method. The main goal here is to have the middle element horizontally centered within its parent element, regardless of other ...

Trying to display logo using 'content' property in CSS

I've been trying to display a logo on the header of my website, but I'm having trouble getting it to show up. I attempted to set the logo using HTML syntax as well as the following CSS code: .div { content: url (...jpg); } However, both metho ...