Reputation: 189
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;");
}
}
Upvotes: 12
Views: 41330
Reputation: 21829
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
Upvotes: 4
Reputation: 469
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");
Upvotes: 24