4

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;
}

1 Answer 1

8

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.