我想用JavaFx创建一些Shapes,我希望每个形状都在其中定义了自己的TranslateTransition对象,当我单击TranslateTransition播放的形状时,我想要那个形状。我的代码:
形状类别:
package com;
import javafx.animation.TranslateTransition;
import javafx.beans.property.DoubleProperty;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.scene.Parent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.util.Duration;
public class MShape extends Parent{
private TranslateTransition Transition;
Circle circle;
DoubleProperty tox;
DoubleProperty toy;
public MShape(int i, int j) {
circle = new Circle(20);
circle.setCenterX(i);
circle.setCenterY(j);
circle.setFill(Color.RED);
Transition= new TranslateTransition();
Transition.setToX(350);
Transition.setToX(375);
Transition.setDuration(Duration.seconds(2));
Transition.setNode(this.circle);
this.getChildren().add(circle);
circle.setOnMouseClicked(new EventHandler<Event>() {
@Override
public void handle(Event paramT) {
Transition.play();
System.out.println("hello");
}
});
}
}
主要阶级
package com;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Test extends Application{
@Override
public void start(Stage stage) throws Exception {
VBox root = new VBox();
stage.setScene(new Scene(root,800,600));
MShape test =new MShape(100, 100);
root.getChildren().add(test);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
问题是当我按形状时它不会移动
最佳答案
不要扩展Parent
。
这对我有用:
public class Test extends Application {
private Circle circle;
private TranslateTransition transition;
@Override
public void start(Stage stage) throws Exception {
/**
* MShape
*/
circle = new Circle(20);
circle.setCenterX(100);
circle.setCenterY(100);
circle.setFill(Color.RED);
transition = new TranslateTransition();
transition.setToX(500);
transition.setToX(500);
transition.setDuration(Duration.seconds(5));
transition.setNode(this.circle);
// this.getChildren().add(circle);
circle.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent paramT) {
transition.play();
System.out.println("hello " + circle.getCenterX() + " " + circle.getCenterY());
}
});
VBox root = new VBox();
Scene scene = new Scene(root, 800, 600);
stage.setScene(scene);
root.getChildren().add(circle);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}