Peter Penzov
Peter Penzov

Reputation: 1668

Cannot load css

I'm testing this code:

LayoutSample.java

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.layout.FlowPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class LayoutSample extends Application
{

    public static void main(String[] args)
    {
        launch(LayoutSample.class, args);
    }

    @Override
    public void start(Stage stage)
    {

        FlowPane flow = new FlowPane();
        flow.setPadding(new Insets(5, 5, 5, 5));
        flow.setVgap(5);
        flow.setHgap(5);
        flow.setPrefWrapLength(170); // preferred width allows for two columns
        flow.setStyle("-fx-background-color: white;");

        //ImageView pages[] = new ImageView[8];
        for (int i = 0; i < 28; i++)
        {
//            pages[i] = new ImageView(
//                    new Image(LayoutSample.class.getResourceAsStream(
//                    "graphics/chart_" + (i + 1) + ".png")));
            flow.getChildren().add(generateRectangle());
        }

        Scene scene = new Scene(flow);
        /////
        String cssURL = "ButtonsDemo.css";
        String css = this.getClass().getResource(cssURL).toExternalForm();
        scene.getStylesheets().add(css);
        ////
        stage.setScene(scene);
        stage.setTitle("Layout Sample");
        stage.show();
    }

    public Rectangle generateRectangle()
    {

        Rectangle rect2 = new Rectangle(10, 10, 10, 10);
        rect2.setId("app");
        rect2.setArcHeight(8);
        rect2.setArcWidth(8);
        rect2.setFill(Color.AZURE);
        //rect2.setX(10);
        //rect2.setY(160);
        rect2.setStrokeWidth(1);
        rect2.setStroke(Color.BLACK);
        rect2.setWidth(220);
        rect2.setHeight(180);

        return rect2;
    }
}

ButtonsDemo.css

#app {
    -fx-background-color:
    linear-gradient(to bottom, #f2f2f2, #d4d4d4);
}

But the css code is not rendered over the Rectangle. Can you tell me this is java code correct. I suspect that I'm not setting the Rectangle Id.

Upvotes: 0

Views: 150

Answers (1)

jewelsea
jewelsea

Reputation: 159290

Your CSS is loaded properly, but your style role is ignored because it is not applicable to the Node type you are trying to apply it to.

To use -fx-background-color, a Node must derive from Region.

A Rectangle is not a Region.

See the CSS reference on Regions and Rectangle for a definition of the attributes applicable for both of those types.

Also, if you use -fx-fill to set the gradient fill for your Rectangle, which I am guessing is what you actually want to do, then you should not also set the fill in source code.

Upvotes: 1

Related Questions