Search code examples
javajavafxattributesgrid-layoutgridpane

How to give CSS attributes to new labels that have not been fully defined?


I have a system of which creates a new Label in Javafx that is predefined but is just created on the spot whenever a method is ran. I want to be able to edit the background color of the label(s) that are created.

countSendResponses++
mainLayout.add(new Label(messageSend), 0, countSendResponces).Color.rgb(1, 1, 1);
// that gives an error, I have tried the same thing in different places in that line of code. Nothing works

My current code: countSendResponses++ mainLayout.add(new Label(messageSend), 0, countSendResponces);

Is there a way to do this? If there is a better way to do what I am doing I am open to suggestions. I want to be able to change the background color of the label. Thank you!


Solution

  • To change the CSS style of any node in JavaFX, you need to use Node.setStyle("//Insert CSS Here.");

    For example, to change the background color of a text, you can use:

    Node.setStyle("
       -fx-background-color: red;
    ");
    

    For a complete reference guide for using CSS in JavaFX, you can go here:

    https://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html#typecolor

    Remember that when using CSS in JavaFX, you always have to start every attribute with -fx-.