How-To's > How do I move objects back and forth?
You can move objects back and forth in two ways.
- To move objects back and forth in a periodic manner, the easiest way is to use the
autoReversevariable of theTranslateTransitionorTimelineclass. Use therepeatCountvariable to determine the number of cycles. - To reverse movement and change the speed at the same time, use the
ratevariable of theTimelineclass. For example, a value of 1.0 is normal play, -1.0 is backward play, and 2.0 is double-time play. Theratevariable is useful when you want to control the moment at which the reverse animation begins, for example in response to a mouse click.
Example Code for autoReverse
The following screen capture and code create the back-and-forth movement of two rectangles. The blue rectangle, controlled by TranslateTransition, moves to the left and back to the right. The orange rectangle, controlled by Timeline, moves to the right and back to the left.

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.shape.Rectangle;
import javafx.scene.paint.Color;
import javafx.animation.transition.TranslateTransition;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
// Use autoReverse and repeatCount in TranslateTransition
def node = Rectangle {
translateX: 50 y: 40
height: 50 width: 50
fill: Color.web("#1F6592")
}
def transTransition = TranslateTransition {
duration: 5s
node: node
byX: -40
repeatCount:Timeline.INDEFINITE
autoReverse: true
}
transTransition.play();
var slider1: Number = 50;
def rect = Rectangle {
translateX: bind slider1 //Horizontal position comes from the keyframes
y: 120 //Vertical position is constant
width: 50,
height: 50
fill: Color.web("#FD8500")
}
//Use Timeline
def t1 = Timeline {
repeatCount:Timeline.INDEFINITE
autoReverse: true
keyFrames: [
KeyFrame {
time: 0s
values: [
slider1 => 50
]
}
KeyFrame {
time: 5s
values: [
slider1 => 90 tween Interpolator.EASEBOTH
]
}
]
};
t1.play();
// Display both the Translate transition and timeline rectangles
Stage {
title: "Animated Square"
width: 300
height: 200
scene: Scene {
content: [
node, rect,
]
}
}
Tips
- For both transitions and timelines, auto reverse counts as one repetition. For example,
repeatCount:2 autoReverse: truehas one forward movement and one backward movement.
API Documentation
Related How-To Topics
- How do I move objects in a straight line?
More information aboutTranslateTransitionandTimeline.
Last Updated: April 2010
[Return to How-To's Home]