Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFx how to use java generated RGB color in CSS

I am working on a project where I try to find the most common color from a picture. My code for finding this works, but I want to set the background color of my scene to the rgb color I found.

I know how to set the background color of my scene using css but I don't have a clue how I can use my methods in there. If it is not possible, is there another way I can set the background color?

The css code right now:

.root{
-fx-background-color: rgb(50,50,50);
-fx-font-size: 11pt; 
}

The JavaFx code right now:

Stage window;

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage primaryStage) throws Exception {
    ColorFinder finder= new CollorFinder("/imgs/picture.jpg");
    int r = finder.rood();
    int g = finder.groen();      //calling my method and setting r g & b
    int b = finder.blauw();

    window = primaryStage;
    window.setTitle("Color");

    Label text = new Label("Most popular color:");
    Label rgb = new Label("rgb("+r+","+g+","+b + ")");



    VBox layout = new VBox(20);
    layout.getChildren().addAll(text,rgb);
    layout.setAlignment(Pos.CENTER);

    Scene scene = new Scene(layout, 300,200);
    String css = gui.class.getResource("styles.css").toExternalForm();
    scene.getStylesheets().add(css);
    window.setScene(scene);
    window.show();
}
}

What I would like to do in css but is not possible:

ColorFinder finder= new CollorFinder("/imgs/picture.jpg");
    int r = finder.rood();
    int g = finder.groen();
    int b = finder
.root{
    -fx-background-color: rgb(r,g,b);
    -fx-font-size: 11pt;
}
like image 232
jdlChicory Avatar asked Mar 09 '23 22:03

jdlChicory


1 Answers

There are two approaches:

  1. Inline style method setStyle(String style):

    layout.setStyle("-fx-background-color: rgb(" + r + "," + g + ", " + b + ");");
    

    r, g, b values range -> (0 - 255)

  2. Method setBackground(Background value):

    layout.setBackground(new Background(new BackgroundFill(Color.rgb(r, g, b), CornerRadii.EMPTY, Insets.EMPTY)));
    

    r, g, b values range -> (0 - 255)

like image 151
MBec Avatar answered Mar 28 '23 04:03

MBec