Question: * * * JavaFX * * * I am trying to make the image bounce around the pane indefinitely, all I can get it to

***JavaFX*** I am trying to make the image bounce around the pane indefinitely, all I can get it to do is either shake or fly off the screen. Help!
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.util.Duration;
public class Jthomas270M6A3 extends Application{
@Override
public void start(Stage primaryStage) throws FileNotFoundException{
InputStream catGraphic = new FileInputStream("src/Graphics/Black_Cat.png");
Image cat = new Image(catGraphic);
ImageView viewableCat = new ImageView(cat);
viewableCat.setFitHeight(100);
viewableCat.setFitWidth(100);
viewableCat.setX(100);
viewableCat.setY(100);
Pane pane = new Pane();
pane.getChildren().add(viewableCat);
Timeline animation = new Timeline(new KeyFrame(Duration.millis(100), new EventHandler(){
double dx =1, dy =1;
@Override
public void handle(ActionEvent e){
viewableCat.setX(viewableCat.getX()+ dx);
viewableCat.setY(viewableCat.getY()+dy);
if(viewableCat.getFitWidth()!= pane.getWidth()){
dx *=-1;
}
if(viewableCat.getFitHeight()!= pane.getHeight()){
dy *=-1;
}
viewableCat.setX(dx);
viewableCat.setY(dy);
}
}));
animation.setCycleCount(Timeline.INDEFINITE);
animation.play();
Scene scene = new Scene(pane,800,600);
primaryStage.setTitle("Bouncing Cat");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args){
launch(args);
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!