Jeremiah Binegar
Jeremiah Binegar

Reputation: 41

Is there a way to give a JavaFX class a new style class, and then access all other objects inside that class normally?

I currently have a JavaFX project I am working on making better with CSS. I have created a few classes that contain other classes inside of it, (i.e. Button, TextField, ScrollPane, etc.)

For ease, lets call this one class Bucket.

Inside of my Bucket class, I also have a Button and TextField.

I have added a new styleClass to bucket by doing:

getScene().getStyleClass().add("bucket");

After doing this, I move to my CSS file, and I want to change the text color of the button inside of my Bucket class.

Do I need to give the button a new StyleClass() as well, or can I access it via:

.bucket > .button { -textColor: white; }

If I can do the latter, how can I get it to work?

Any help is appreciated!

Upvotes: 1

Views: 122

Answers (1)

Slaw
Slaw

Reputation: 45806

Assuming Bucket looks something like:

public class Bucket extends Region { // or extends Pane, Control, some other Parent

  public Bucket() {
    getStyleClass().add("bucket");

    Button button = new Button("Some text");
    getChildren().add(button);
  }
}

Then yes, you would use:

.bucket > .button {
  -fx-text-fill: <your-color>;
}

If the button is not a direct child of Bucket then get rid of the >. Not sure how to answer: "If I can do the latter, how can I get it to work?". You can do the latter and that is how you get it to work (though your example isn't using the correct CSS property).

Note that getStyleClass().add("some-style-class") is how every single node is assigned a style class. So you doing the exact same thing will work with the API.

For more information, see the JavaFX CSS Reference Guide.

Upvotes: 2

Related Questions