Search code examples
javatextjavafxlabelfade

Using a FadeTransition on a Label causes the Label to appear different at start of transition


I need either a Label or a Text for my project. I need the label so that ellipsis can be used. The problem though, is when I try to use a FadeTransition, and play it, the label gets slightly darker at the start. Here is some demo code:

package com.neonorb.test;

import javafx.animation.FadeTransition;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.IOException;

/**
 * Created by chris on 7/20/15.
 */
public class Test extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws IOException {
        Label label = new Label("hello");
        //Text label = new Text("hello);//Using Text instead of Label does not cause the weird behavior
        FadeTransition fadeTransition = new FadeTransition(Duration.seconds(3), label);
        fadeTransition.setFromValue(1.0);
        fadeTransition.setToValue(0.0);
        fadeTransition.setOnFinished(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                label.setOpacity(1.0);
            }
        });
        Button button = new Button("play");
        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                fadeTransition.play();
            }
        });
        BorderPane borderPane = new BorderPane();
        borderPane.setCenter(label);
        borderPane.setBottom(button);
        primaryStage.setScene(new Scene(borderPane));
        primaryStage.show();
    }
}

So I either need a fix to this problem, or a way to use ellipsis in Text. Any ideas?


Solution

  • Set the opacity of the label to 0.99 initially:

    label.setOpacity(0.99);
    

    Also change the code inside setOnFinished method in the same way. Then, set the starting value of the fade transition to 0.99:

    fadeTransition.setFromValue(0.99);
    

    I know this is not the solution you are looking for, but this solution prevents the label from abruptly getting darker at the start. That is because the label actually starts with that darker status.