12

How can I set a CSS style for a class which extends a JavaFX object?

public class DiagramPane extends ScrollPane implements IDiagramEditor {
    // .... Methods go here
}

I've tried the following ways in the main method:

public class DiagramPane extends ScrollPane implements IDiagramEditor {
    DiagramPane() {
        this.setStyle("-fx-background-color: #f8ecc2;-fx-font-size: 8pt;");
        setStyle("-fx-background-color: #f8ecc2;-fx-font-size: 8pt;");
    }
}

2 Answers 2

25

Add these lines to your css file

.diagram-pane {
    -fx-background-color: #f8ecc2;
    -fx-font-size: 8pt;
}

and set DiagramPane instance to use diagram-pane style class

diagramPane.getStyleClass().clear();
diagramPane.getStyleClass().add("diagram-pane");
Sign up to request clarification or add additional context in comments.

1 Comment

does not answere question, i too am looking for a way to have a CLASS return a style - string, not include some css files
4

One of the possibilities is what you have mentioned to use setStyle method of Node.

public class MyScrollPane extends ScrollPane {

    public MyScrollPane(){
        setStyle("-fx-background-color: blue;");
    }

}

Another possibility to use a CSS stylesheet

This one is the suggested approach, as it totally separates the CSS styling from the Java code.

Note: MyScrollPane.css is placed in the same directory as the class itself.

MyScrollPane.java

public class MyScrollPane extends ScrollPane {

    public MyScrollPane(){
        getStylesheets().add(getClass().getResource("MyScrollPane.css").toExternalForm());
    }

}

In this stylesheet you can overwrite the existing CSS classes of the ScrollPane like:

MyScrollPane.css

.scroll-pane {
    -fx-background-color: red, white;
    -fx-background-insets: 0, 2;
    -fx-padding: 2.0;
}

To check which classes exist for scroll pane in JavaFX you can read the caspian.css. The base class for ScrollPane is .scroll-pane.

Also you can define new CSS classes and add them to your ScrollPane:

public class MyScrollPane extends ScrollPane {

    public MyScrollPane(){
        getStylesheets().add(getClass().getResource("MyScrollPane.css").toExternalForm());
        getStyleClass().add("red-border");
    }

}

And in CSS

.red-border {
    -fx-background-color: red, white;
    -fx-background-insets: 0, 2;
    -fx-padding: 2.0;
}

To learn about CSS styling in JavaFX: http://docs.oracle.com/javafx/2/css_tutorial/jfxpub-css_tutorial.htm

Also you can check the CSS Reference Guide for JavaFX: https://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html

1 Comment

can't u use setUserAgentStylesheet nowadays?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.