purring pigeon
purring pigeon

Reputation: 4209

Can I convert a CSS style to an Image in JavaFX 8

I have a window launcher which is created dynamically and the toolbar buttons are styled with the following CSS for example:

.toolbar-button-open-notepad {
    -fx-background-image:  url("../images/buttons/notebook_edit.png");
    -fx-background-size: 24,24;
    -fx-background-position: center center;
    -fx-background-repeat: no-repeat;

     -fx-min-width:24;
    -fx-min-height:24;
    -fx-pref-height:24;
    -fx-pref-width:24;
    -fx-max-height:24;
    -fx-max-width:24;
}

What I would like to do is set the stage.getIcons().add() to the image stored in this css reference. However I have not been able to find away to do that. Is there a way to get that information so that I don't need to hardcode references to my images in my code?

Thanks.

Upvotes: 0

Views: 401

Answers (2)

José Pereda
José Pereda

Reputation: 45456

Once you have applied CSS to your scene, retrieving the image assigned to a given node through the property -fx-background-image can be done easily just by using the Node.getBackground().getImages() method.

This simple test shows how this can be done.

@Override
public void start(Stage primaryStage) {
    Button btn = new Button();
    btn.setText("Say 'Hello World'");
    btn.setOnAction(e -> System.out.println("Hello World!"));

    VBox box = new VBox(btn);
    box.getStyleClass().add("box");

    StackPane root = new StackPane();
    root.setPadding(new Insets(20));
    root.getChildren().add(box);

    Scene scene = new Scene(root, 300, 250);
    scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());

    primaryStage.setTitle("Hello World!");
    primaryStage.setScene(scene);
    primaryStage.show();

    Region node = (Region) root.lookup(".box");
    if (node != null) {
        Image image = node.getBackground().getImages().get(0).getImage();
        System.out.println("Image " + image);
    }
}

where style.css is just:

.box {
    -fx-background-image: url("icon.png");
    -fx-background-size: stretch;
}

Note this has to be done after the stage is shown. Otherwise you will need to have the node added to the scene and call root.applyCSS() and root.layout() before calling the lookup.

Upvotes: 1

Hendrik Ebbers
Hendrik Ebbers

Reputation: 2600

You could create a Class ExtendedStage extends Stage that contains a new StyleableProperty that holds the image.

Upvotes: 0

Related Questions