Home > Java FX 2 > Linking a CSS Style Sheet to JavaFx Scene Graph

Linking a CSS Style Sheet to JavaFx Scene Graph

The recommended way to link your CSS styles to a Scene Graph in your application is through the stylesheets variable.

Set your css paths relative to your application’s concrete class. This is the class that will extend Application. In the sample project pictured below, the Concrete Application Class is my Driver.java file.

For more information on working with CSS Style Sheets in JavaFX 2 applications please see my article on JavaDesk website. I provide an example where a user can swap Style Sheets dynamically using a ChangeListener.

Driver.java has the class declaration:

public class Driver extends Application {public static void main(String[] args) {
public void start(Stage primaryStage) {}

Example 1: Connect to CSS Style Sheet in same Package

//Demonstrate in one long line of code.

//Break up into two lines of code.
String cssURL = this.getClass().getResource(“Styles.css”)

//Replace this keyword with full URL of main class.

Example 2: Connect to CSS Style Sheet in another Package

//Get a style sheet that is not in same package as Driver.

Example 3: Get Multiple CSS Style Sheets

//Use addAll() to attach several stylesheets.
String cssFile1 = this.getClass().getResource(“x.css”)
.toExternalForm();String cssFile2 = this.getClass().getResource(“Styles.css”)
.toExternalForm();String cssFile3 = this.getClass().getResource(“/cssStyles/base.css”)
.toExternalForm();scene.getStylesheets().addAll(cssFile1, cssFile2, cssFile3);

Categories: Java FX 2 Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: