Encountering a NullPointerException while trying to load a resource from a directory that is not within

I'm working with JavaFX and trying to incorporate a CSS file into my scene.

scene.getStyleSheets().add(Main.class.getResource("res/application.css").toExternalForm();

An NPE is being thrown. I suspect it's because the css file isn't located within the classpath. But I'm unsure how to tackle loading it in this manner. I prefer not to have the css file in my package directory (com.somecompany.package). Instead, I'd like it to be in a separate directory for independent deployment (allowing users to modify if needed).

Is there a way to load a css file (or any resource) from outside the classpath?

Here is my stack trace:

java.lang.NullPointerException
        at com.somecompany.someapp.Main.start(Main.java:30)
        at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
        at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:206)
        at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:173)
        at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
        at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:29)
        at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:73)
    at java.lang.Thread.run(Unknown Source)

Answer №1

To search for a resource at the root of the classpath, add a / at the beginning of the String argument.

scene.getStyleSheets().add(Main.class.getResource("/res/application.css").toExternalForm();

If not using the root path, the resource is resolved relative to the package that contains Main. Details on how resources are resolved can be found in the javadoc.

If you need to modify the file, it's best to get it from the file system instead.

Path path = Paths.get("/path/to/file");     
scene.getStyleSheets().add(path.toUri().toURL()).toExternalForm();

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

Encountering difficulties in compiling Selenium standalone with Java 11

My attempts to create a Java Selenium standalone application using Java11 in Eclipse 2018-12 have been met with failure: java.lang.module.FindException: Unable to derive module descriptor for \selenium-server-standalone-3.141.59.jar I am explori ...

What is the best way to embed a section of another website within an iframe and seamlessly guide a user to complete a purchase using a shopping cart?

Seeking advice on how to improve the functionality of my website. Currently, the domain I'm focusing on serves as a landing page, redirecting users to another site for purchases. I've built a separate website for this domain in order to establis ...

Adjust the background shade of the HTML <area> tag

I have an image containing over 100 geometrical shapes, each with unique sizes and dimensions. I utilized image mapping to assign IDs to each <area> tag such as <area id="1">. I stored information in a MySQL database about each shape, ...

What is the best way to include a text input as the last option in a Select input form field?

I would like to implement a select input feature where users can choose from predefined options, with the added functionality of including a text input field as the last option for users who prefer to enter their own category. How can I achieve this? Curr ...

React component rendering twice due to width awareness

In a React component that I've developed, I have utilized ResizeObserver to track its own width. Within this component, two divs are rendered with each having a "flex: 1" property to ensure equal width distribution. Under certain conditions, such as w ...

jQuery Summation: A Step-by-Step Guide

Hello everyone, I am a new member of this forum and I am looking forward to learning and contributing with all of you. I have encountered a problem that I tried to solve on my own but couldn't figure it out. Would anyone be able to lend me a hand? H ...

Ways to connect css file to ejs views in nodejs

Currently, I am tackling a beginner node.js server project. While I have successfully managed to render dynamic HTML using ejs templates, I seem to be facing difficulties when it comes to linking CSS styling to these templates. In an effort to address thi ...

How can I create an encrypted message on an Android device?

Is there a way to format a string like "abc 123 def" as "abc%20123%20def" for use in an http request query parameter? https://myBaseUrl.com?parameter=abc%20123%20def" If I try using the code below: val myString = "321 pop&quo ...

ngSwitchCase provider not found

While following a tutorial and trying to implement what I learned, I encountered an error that I'm having trouble understanding. The browser console shows an error message stating [ERROR ->]<span *ngSwitchCase="true">, but I can't figure ...

Personalizing the pop-up window using window.open

When clicking a hyperlink on a page, I need to open multiple pop-up windows. To achieve this, I must use the Window.open function instead of showModalDialog. However, I have noticed that the appearance is not satisfactory when using Window.open. (Essentia ...

The proper method to set focus on an element when using Selenium WebDriver with Java

Is there a universal alternative to selenium.focus() for WebDriver? element.sendKeys(""); or new Actions(driver).moveToElement(element).perform(); I have experimented with both methods and they have both been successful. However, which one is more rel ...

Utilize regex to substitute the first instance of a character within a word that is not at the start

For instance: When "initial" becomes "ineetial", "alumni" becomes "alumnee", and "illuminati" becomes "illumeenati." Yet, by employing this code: str = str.replaceAll("(\\w+)i(.?)", "$1ee$2"); I consistently receive 'initeeal', &apo ...

The CSS :active selector glutton

Within a <div> element, I have an <img>. I would like the entire div to scale down by 10% (using transform) when clicked on. While I have achieved this effect, there is one minor issue: clicking on the image itself does not trigger the scaling, ...

I'm having trouble adjusting the link color in my footer text while navigating Wordpress for the first time

As someone who is new to Wordpress, I am struggling with changing the link color in the footer text. Despite spending hours on it, I just can't seem to figure it out. The files I have been working with are style.css and bootstrap.min.css. I feel lik ...

Step-by-step guide to implementing a floating action button on the bottom-right corner of a screen using Material-UI in a React application

I have been attempting to place the FloatingActionButton on the bottom right corner of the screen. To achieve this, I am utilizing the following library: http://www.material-ui.com/#/components/floating-action-button import React, { Component } from "reac ...

Obtaining a class value from a text box with Webdriver in Java

Testing condition - verifying field validation by entering invalid data in a Text box, capturing the Exception value and checking if it matches "Please enter first name". Here is my HTML code: Before executing validation <input type="text" class="inpu ...

Merging the Select and Input elements side by side using Bootstrap grid system

Is there a way to combine all form group items like Select and Input using only the bootstrap framework? I attempted the method below, but there is an extra space between the Select and Input Box. Check out the DEMO ...

The navigation menu dissolves into hiding at the uppermost part of the page upon scrolling upwards on iOS devices

I am currently working on creating a navigation menu that will automatically hide when scrolling down and reappear when scrolling up. This functionality works perfectly fine on desktop and Android browsers, but I have encountered an issue specifically with ...

The integration of CSS into Laravel was unsuccessful

Below is the content of my index file located in views.admin: <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet&qu ...

Using Java to extract data from a massive file and distribute it across various smaller files

I have a file named A.txt containing 100,000,000 records ranging from 1 to 100,000,000, with each record on a separate line. My task is to read the contents of file A and write them to files B and C in such a way that even-numbered lines go to file B and o ...