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;");
}
}
The default css is always applied to every JavaFX application. However, you can create one or more custom stylesheets of your own and add them to your application to override the default styles defined by JavaFX.
In Scene Builder, you can simulate the attachment of a style sheet to an application Scene by selecting Preview, then Scene Style Sheets, and finally choosing Add a Style Sheet or Open a Style Sheet option. This Preview command is useful when the “root” style class is defined in the style sheet.
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");
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With