Get the background color of a JavaFX control

1

I want to read the background color of a control from javaFX code and then apply a transparency to it. I have been looking for information but I do not clarify. There is no method getBackgroundColor() but if getBackground() even if I'm lost any idea?

    
asked by Oundroni 16.02.2016 в 15:44
source

2 answers

1

See if this is what you need in this link: window with shaded edges

The part that you should look at carefully is:

stage.initStyle(StageStyle.TRANSPARENT);

and

// Establecer el color de relleno del Scene a transparente
scene.setFill(Color.TRANSPARENT);
    
answered by 16.02.2016 в 16:21
0

Sorry for the kilometric response, I had not used JavaFX for a long time and therefore I did a little more research.

Short answer:

You can get the colors used for the background to use getBackground method, which in turn has a list of the colors used, and unless you are using a gradient or something similar, the first fill should be the Unique background color of your object.

Color color = (Color) boton.getBackground().getFills().get(0).getFill();
System.out.println("color:"+color);

Long answer:

It is important that you differentiate between the color that is set programmatically and the one that is set in style , since the styles have a greater preference than the normal background colors and can produce subtle errors, which may or may not work in our favor and I always suggest using programmatic colors in instead of javafx css styles.

Let's see a simple example, if you have a fxml with a button like this:

<Button fx:id="btnrojillo" layoutX="16.0" layoutY="128.0" mnemonicParsing="false" onAction="#handleSubmitButtonAction" style="-fx-background-color: blue;" text="Button" />

and in your button handles you can read something like:

@FXML
protected void handleSubmitButtonAction(ActionEvent event) {
    String style = btnrojillo.getStyle();

    System.out.println(style);
    btnrojillo.setStyle("-fx-background-color: red;");
    String colorDesdeEstilo = style.replaceAll(".*(-fx-background-color:\s?([a-zA-Z0-9]+)).*", "$2");


    System.out.println("color detectado desde hoja de estilos:" +
            colorDesdeEstilo
    );

    Color color = (Color) btnrojillo.getBackground().getFills().get(0).getFill();
    System.out.println("color detectado desde configuración de componente:" + color.toString().substring(2));
}

The first time you run it you'll get a very awful NPE (It's not what you think itchy;)) like this:

  

Caused by: java.lang.NullPointerException

     

at swinginterop.Model.handleSubmitButtonAction

Now if we put a color selector to our

answered by 16.12.2018 в 00:04