问题
I have a Circle
and its centerX
property is bound to the text
property of a label. This is for viewing the position of the object on screen. The binding seems to stop working whenever I apply a transition on the circle. This is a snippet from the code.
//ERRONEOUS PART OF CODE
Circle circle = new Circle(50, 20, 20);
Label posLabel = new Label();
//binding
StringBinding binding = new StringBinding(){
{bind(circle.centerXProperty());}
@Override public String computeValue(){
return Double.toString(circle.getCenterX());
}
};
posLabel.textProperty().bind(binding);
//translation
TranslateTransition transition = new TranslateTransition(Duration.seconds(3), circle);
transition.setByX(250);
transition.play();
I would like to know why bindings don't work with transitions, and if possible, a workaround to the problem.
P.S. A complete minimum reproducible example: (I am saying that the binding doesn't work because the labels value is stuck at 50.0)
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import javafx.scene.control.Label;
import javafx.scene.shape.Circle;
import javafx.animation.TranslateTransition;
import javafx.util.Duration;
import javafx.beans.binding.StringBinding;
public class TransitionError extends Application
{
public void start(Stage stage) throws Exception
{
//instantiating all objects
Circle circle = new Circle(50, 20, 20);
Label posLabel = new Label();
Group group = new Group(circle, posLabel);
Scene scene = new Scene(group, 300,100);
stage.setTitle("JavaFX Example");
stage.setFullScreen(true);
stage.setScene(scene);
stage.show();
//ERRONEOUS PART OF CODE
//binding
StringBinding binding = new StringBinding(){
{bind(circle.centerXProperty());}
@Override public String computeValue(){
return Double.toString(circle.getCenterX());
}
};
posLabel.textProperty().bind(binding);
//translation
TranslateTransition transition = new TranslateTransition(Duration.seconds(3), circle);
transition.setByX(250);
transition.play();
}
}
回答1:
The TranslateTransition
doesn't change the value of centerX
; it changes the value of translateX
.
So you could do:
StringBinding binding = new StringBinding(){
{bind(circle.centerXProperty(), circle.translateXProperty());}
@Override public String computeValue(){
return Double.toString(circle.getCenterX()+circle.getTranslateX());
}
};
Or you could use your original binding and animate the centerX
property instead (this may be preferable, since you seem to be relying on centerX
to change):
// TranslateTransition transition = new TranslateTransition(Duration.seconds(3), circle);
// transition.setByX(250);
// transition.play();
Timeline timeline = new Timeline(new KeyFrame(
Duration.seconds(3),
new KeyValue(circle.centerXProperty(), circle.getCenterX()+250)
));
timeline.play();
来源:https://stackoverflow.com/questions/65360588/why-arent-bindings-working-with-transitions