so I am trying to create a snowman and animate its left and right arm, I have looked at the Oracle docs and tried to write my time as closely as possible to how the example sets it.
For reference, this is the code example I was looking at:
final Rectangle rectBasicTimeline = new Rectangle(100, 50, 100, 50);
rectBasicTimeline.setFill(Color.RED);
...
final Timeline timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.setAutoReverse(true);
final KeyValue kv = new KeyValue(rectBasicTimeline.xProperty(), 300);
final KeyFrame kf = new KeyFrame(Duration.millis(500), kv);
timeline.getKeyFrames().add(kf);
timeline.play();
Now, here is my code for creating the left arm, and (if it worked) animating it. Where is my flaw and how can I fix it?
private void drawLeftArm(GraphicsContext gc)
{
leftArm = new Ellipse();
leftArm.setCenterX(90.0);
leftArm.setCenterY(160.0);
leftArm.setRadiusX(100.0);
leftArm.setRadiusY(30.0);
gc.setFill(Color.AQUAMARINE);
gc.fillOval(leftArm.getCenterX(), leftArm.getCenterY(), leftArm.getRadiusX(), leftArm.getRadiusY());
timeLine = new Timeline();
timeLine.setCycleCount(Timeline.INDEFINITE);
timeLine.setAutoReverse(true);
KeyValue LeftValue = new KeyValue(leftArm.centerYProperty(), 100);
KeyFrame keyFrame = new KeyFrame(Duration.millis(1000), LeftValue);
timeLine.getKeyFrames().addAll(keyFrame);
timeLine.play();
}
In the code you posted, you created leftArm
, but did not add it to the scene graph. As a result, it is animating, but not visible. The fillOval
call above is equivalent to
gc.fillOval(90.0, 160.0, 100.0, 30.0);
in the sense that it does not have any reference to leftArm
. So you did two (independent) things: painted an oval to the canvas and started animation of an invisible ellipse.
For animations, don't use Canvas
/GraphicsContext
. Just use a Group or Pane as a parent for the animated nodes.