Issue
I have this simple class:
Test.java:
import javafx.animation.FadeTransition;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.util.Duration;
public class Test extends Application {
@Override
public void start(Stage stage) throws Exception {
Pane pane = new Pane();
Button testButton = new Button("Test");
testButton.setStyle("-fx-background-color: green;");
pane.getChildren().add(testButton);
pane.setStyle("-fx-background-color: red;");
FadeTransition transition = new FadeTransition(Duration.millis(5000), pane);
transition.setFromValue(1.0);
transition.setToValue(0.0);
transition.setCycleCount(Timeline.INDEFINITE);
transition.setAutoReverse(true);
transition.play();
Scene scene = new Scene(pane, 500, 500);
stage.setMinWidth(500);
stage.setMinHeight(500);
stage.setTitle("Test");
stage.setResizable(false);
stage.setScene(scene);
stage.show();
}
}
It looks like this:
when it fades however it becomes this:
How do I make it so that the fade transition only affects the red background and doesn't affect the green button?
So that it looks like this:
Solution
using stackpane
You can use StackPane
as root and both : Pane
and Button
children of stackpane . Button is not affected by transition since is no longer child of pane .
if you need different aligments for different nodes you can use static method setAligment from StackPane class , wich requires a child node and position as arguments
public class App extends Application {
@Override
public void start(Stage stage) throws Exception {
Pane pane = new Pane();
Button testButton = new Button("Test");
testButton.setStyle("-fx-background-color: green;");
StackPane stackPane = new StackPane(pane,testButton);
stackPane.setAlignment(Pos.TOP_LEFT);
pane.setStyle("-fx-background-color: red;");
FadeTransition transition = new FadeTransition(Duration.millis(5000), pane);
transition.setFromValue(1.0);
transition.setToValue(0.0);
transition.setCycleCount(Timeline.INDEFINITE);
transition.setAutoReverse(true);
transition.play();
Scene scene = new Scene(stackPane, 500, 500);
stage.setMinWidth(500);
stage.setMinHeight(500);
stage.setTitle("Test");
stage.setResizable(false);
stage.setScene(scene);
stage.show();
}
}
Answered By - Giovanni Contreras
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)