How to attach a CSS stylesheet to FXML?


Question

Following Oracle tutorial http://docs.oracle.com/javafx/2/get_started/fxml_tutorial.htm, I create FXML with a fragment

<?xml version="1.0" encoding="UTF-8"?>

<?language javascript?>

<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.geometry.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.text.*?>

<GridPane alignment="CENTER" gridLinesVisible="true" hgap="10.0" vgap="10.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" fx:controller="fxmlexample.FXMLExampleController" styleClass="root" >
...other stuff...
<stylesheets>
    <URL value="@Login.css" />
</stylesheets>
</GridPane>

NetBeans 8.0 colors the URL red and says: "Class does not exist: URL".

When compiled and run, JRE 1.8 also throws an exception:

...
Caused by: java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:894)
    at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:56)
    at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:158)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javafx.fxml.LoadException: URL is not a valid type.
file:/C:/Users/User1/Documents/NetBeansProjects/FXMLExample/dist/run1970052180/FXMLExample.jar!/fxmlexample/fxml_example.fxml:46

If I open the fxml_example.fxml file in JavaFX Scene Builder 1.1", it also complains about missing types, elements of which will not be shown:

Missing types are: [URL]

Everyone seems to be using <URL/> elements, why cannot I?

1
6
5/5/2014 3:03:46 PM

Accepted Answer

URL is a class in the java.net package; you should import it from the FXML:

<?import java.net.*?>
20
5/5/2014 3:19:57 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon