Basic Animation: Creating a shape animation in JavaFX
Write a JavaFX application that animates a shape (e.g., a circle) to move across the window in response to a button click.
Sample Solution:
JavaFx Code:
Main.java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.animation.TranslateTransition;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Shape Animation");
Pane root = new Pane();
// Create a circle to animate.
Circle circle = new Circle(50, Color.RED);
circle.setCenterX(50);
circle.setCenterY(100);
// Create a button to start the animation.
Button startButton = new Button("Start Animation");
startButton.setLayoutX(150);
startButton.setLayoutY(250);
// Create a TranslateTransition for the circle.
TranslateTransition translateTransition = new TranslateTransition(Duration.seconds(2), circle);
// Set the target location for the animation.
translateTransition.setToX(250);
translateTransition.setAutoReverse(true);
translateTransition.setCycleCount(TranslateTransition.INDEFINITE);
// Handle the button click to start the animation.
startButton.setOnAction(event -> {
if (!translateTransition.getStatus().equals(TranslateTransition.Status.RUNNING)) {
translateTransition.play();
}
});
root.getChildren().addAll(circle, startButton);
Scene scene = new Scene(root, 300, 300);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Explanation:
In the exercise above -
- Import the necessary JavaFX libraries.
- Create a class "Main" that extends "Application" and overrides the "start()" method.
- Inside the "start()" method:
- Set the title of the application window to "Shape Animation."
- Create a 'Pane' named 'root' to serve as the root container for the application's UI elements.
- Create a blue circle with a radius of 50, and set its initial position.
- Create a button labeled "Start Animation" and position it.
- Create a TranslateTransition named translateTransition to control the animation of the circle. The animation will move the circle from its initial position to the target position (toX).
- Handle the button click to start the animation. The animation is played only if it's not already running.
- Add the circle and the button to the root container.
- Create a JavaFX Scene named 'scene' with the 'root' layout, setting its dimensions to 300x300 pixels.
- Set the created scene in the primary stage (primaryStage) and show the window.
Sample Output:
Flowchart:
![Flowchart: Main.java - Basic Animation: Creating a shape animation in JavaFX.](https://www.w3resource.com/w3r_images/javafx-basic-flowchart-exercise-10.png)
Java Code Editor:
Previous:Event Handling: Creating a Clickable Circle in JavaFX.
//------------- this portion above included on 07-02-2025 ------------------------------
var new_txt = 'Based on '+total_submit+' votes, average difficulty level of this exercise is '+difficulty+'.';
//'. '+difficulty+'/3';
var txt_node = document.createTextNode(new_txt);
var level_result = document.getElementById('level_result');
level_result.appendChild(txt_node);
}
}
else {
alert('There was a problem with the request.');
}
}
}
}
function insert_level(event) {
event.preventDefault();
var path = window.location;
var page = path.href;
var page = page.split('?');
var page = page[0];
//console.log(page);
//console.log(page);
/*var btns = document.getElementsByClassName("mdl-button mdl-js-button mdl-button--raised mdl-button--colored");
for (var i = 0; i < btns.length; i++) {
var clicked = btns[i].id;
}*/
var clicked = this.id;
if(clicked=="easy")
clicked=1;
if(clicked=="medium")
clicked=2;
if(clicked=="hard")
clicked=3;
console.log(clicked);
var httpRequest1 = new XMLHttpRequest();
if (!httpRequest1) {
alert('Giving up :( Cannot create an XMLHTTP instance');
//return false;
}
var url = "/assets/level_insert.php";
var data1 = "level=" + clicked + "&page=" + page;
httpRequest1.onreadystatechange = displayContent1;
httpRequest1.open("POST", url, true);
httpRequest1.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpRequest1.send(data1);
console.log(data1);
//console.log("found");
function displayContent1(responseText) {
if (httpRequest1.readyState === XMLHttpRequest.DONE) {
if (httpRequest1.status === 200) {
var op = httpRequest1.responseText;
console.log(op);
} else {
alert('There was a problem with the request.');
}
}
}
}
var easy = document.getElementById("easy");
easy.addEventListener('click', insert_level, false);
var medium = document.getElementById("medium");
medium.addEventListener('click', insert_level, false);
var hard = document.getElementById("hard");
hard.addEventListener('click', insert_level, false);
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics