How can I apply a certain style for all lines objects in a separate css file for a javaFX project? This is the java code :
package com.example.demo;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
import java.io.IOException;
public class HelloApplication extends Application {
@Override
public void start(Stage stage) throws IOException {
Pane root = new Pane();
Scene scene = new Scene(root, 1200, 800);
stage.setTitle("Simulink viewer");
Label l1 = new Label("hdkhsd");
l1.setLayoutX(100);
l1.setLayoutY(100);
Label l2 = new Label("helle");
l2.setLayoutX(400);
l2.setLayoutY(400);
root.getChildren().addAll(l1,l2);
Line l = new Line(10,10,90,90);
root.getChildren().add(l);
scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
And this is the css file:
.root{
-fx-background-color : #ADD8E6;
}
.label {
-fx-border-color: red;
}
.line {
-fx-stroke = green;
}
The style works for both root and label, but it doesn't work for line. What is the problem?
I'm having this warning:
May 13, 2023 4:31:05 PM javafx.css.CssParser declaration WARNING: CSS Error parsing file:/E:/College/Now/Advanced/Projects/normal%20java%20projects/demo/target/classes/com/example/demo/style.css: Expected COLON at [10,11]
I actually read that style class for line is empty by default. What does that mean? Does it mean I can't style line in a separate css file?
First, note you have a syntax error in your CSS file:
-fx-stroke = green;
should be
-fx-stroke: green;
Additionally, note from the documentation that the style class of Line
is empty by default. (Only Control
and its subclasses, along with ImageView
, WebView
, and MediaView
have default style classes.) Consequently, the selector will not select the line. You can either add the style class to the line explicitly:
Line l = new Line(10,10,90,90);
l.getStyleClass().add("line");
or us a Type Selector. From the documentation:
Node's getTypeSelector method returns a String which is analogous to a CSS Type Selector. By default, this method returns the simple name of the class.
So the following will work without adding the style class in the Java code:
Line {
-fx-stroke: green;
}