wem18
wem18

Reputation: 73

How do you change a JavaFX Label's textFill with a KeyFrame?

So I generally understand that a keyframe constructor takes in the node property and desired end value.

For example:

new KeyFrame(Duration.seconds(2), new KeyValue(YourNode.layoutXProperty, 75));

However, Label.textFill does not exist, and getTextFill is a getter, not a member variable. Is there any way to get around this?

The code would work something like:

new KeyFrame(Duration.seconds(2), new KeyValue(YourNode.textFill, Color.GREEN));

Upvotes: 1

Views: 973

Answers (1)

James_D
James_D

Reputation: 209408

The pattern for method naming for a JavaFX property xxx of type T is:

public Property<T> xxxProperty() // returns the property itself
public T getXxx() // returns the value of the property
public void setXxx(T x) // sets the value of the property

So, for example, for the textFill property which Label inherits from Labeled, there is a public ObjectProperty<Paint> textFillProperty() method, returning the actual property.

So all you need is

new KeyFrame(Duration.seconds(2), new KeyValue(label.textFillProperty(), Color.GREEN))

SSCCE:

import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;

public class TextFillTransition extends Application {

    @Override
    public void start(Stage primaryStage) {
        Label label = new Label("Transitioning the fill of a label");
        label.setStyle("-fx-font-size: 24pt ;");

        Timeline timeline = new Timeline(
            new KeyFrame(Duration.seconds(0), new KeyValue(label.textFillProperty(), Color.RED)),
            new KeyFrame(Duration.seconds(2), new KeyValue(label.textFillProperty(), Color.GREEN))
        );
        timeline.setAutoReverse(true);
        timeline.setCycleCount(Animation.INDEFINITE);
        timeline.play();

        StackPane root = new StackPane(label);
        root.setPadding(new Insets(12));
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

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

enter image description here

Upvotes: 2

Related Questions