Write a JavaFX program that moves an image toward the location of the mouse. The image shouldnt
Question:
Write a JavaFX program that moves an image toward the location of the mouse. The image shouldn’t jump directly to the mouse coordinates (which is what happens in Listing 9.16) but should move a few pixels toward the mouse location every time cycle. You can choose the time cycle to control the speed of the animation.
Listing 9.16
import javafx.application.Application;
import javafx.scene.canvas.Canvas;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.input.MouseEvent;
import javafx.event.EventHandler;
import javafx.scene.shape.Circle;
/**
This program sets the X/Y coordinates of a Circle to the
location of the mouse.
*/
public class MouseCircle extends Application
{
public static void main(String[] args)
{
Application.launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception
{
Pane root = new Pane();
root.setPrefSize(400,400);
Circle circle = new Circle();
circle.setRadius(30);
circle.setFill(Color.RED);
root.setOnMouseMoved(new EventHandler()
{
@Override
public void handle(MouseEvent event)
{
circle.setCenterX(event.getX());
circle.setCenterY(event.getY());
}
});
root.getChildren().add(circle);
primaryStage.setScene(new Scene(root));
primaryStage.setTitle("Mouse Circle");
primaryStage.show();
}
}
Step by Step Answer:
Java An Introduction To Problem Solving And Programming
ISBN: 9780134462035
8th Edition
Authors: Walter Savitch