Question

In: Computer Science

This lab is designed to design an event driven animation application which JavaFX application implementing a...

This lab is designed to design an event driven animation application which JavaFX application implementing a racing car image. The car moves from left to right. When it hits the right end, it restarts from the left and continues the same process. Let the user pause/resume the animation with a button press/release and increase/decrease the car speed by pressing the up and down arrow keys.

The car used for this application has the following attributes.


Task(s)
Task 1: Create a JavaFX application called ‘CarRacing’.

Task 2A: Create a class called ‘CarPane’ which extends ‘Pane’, which defines the attributes of the car. The class will have multiple instance variables, which will be tied to width and height of the pane. If the window
private double paneWidth = 200; // Width of the pane
private double paneHeight = 200; // Height of the pane
private double baseX = 0; // Initial X placement of Car
private double baseY = paneHeight; // Initial y placement of Car
private Circle c1 = new Circle(baseX+15, baseY-5, 5); // Placement of first wheel
private Circle c2 = new Circle(baseX+35, baseY-5, 5); // Placement of second wheel
private Rectangle carBody = new Rectangle( baseX, baseY-20, 50, 10); // Car body
private Polygon carTop = new Polygon( baseX+10, baseY-20, // Car top
baseX+20, baseY-30, baseX+30, baseY-30,
baseX+40, baseY-20);   

Task 2B: Define a constructor which sets the color and places the tires, the body and the top on the pane
public CarPane()
{
carBody.setFill( Color.CYAN );
carTop.setFill( Color.BLUE );
this.getChildren().addAll( c1, c2, carBody, carTop );
}

Task 2C: Define a CarPane method called setValues(), which clears the previous painting of the car and re-paints the car with the newest position.
public void setValues()
{
c1.setCenterX( baseX+15 );
c1.setCenterY( baseY-5 );
c2.setCenterX( baseX+35 );
c2.setCenterY( baseY-5 );
  
carBody.setX( baseX );
carBody.setY( baseY-20 );
  
carTop.getPoints().clear();
carTop.getPoints().addAll( baseX+10, baseY-20,
baseX+20, baseY-30, baseX+30, baseY-30,
baseX+40, baseY-20);   
}

Task 3: Create a new Pane, along with a scene. Run the application which should paint the pane with the automobile in the lower left hand position. Try resizing the window, the car should maintain its position.
// Create a new CarPane
CarPane car = new CarPane();
  
// Create a scene and place it in the stage
Scene scene = new Scene(car, 200, 200);
primaryStage.setTitle("Racing Car"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage

Task 4: Create an animation, which initializes the animation, sets the timeline cycle and starts the animation.
Timeline animation = new Timeline( new KeyFrame(Duration.millis(100), e->car.move()));
animation.setCycleCount( Timeline.INDEFINITE );
animation.play(); // Start animation
The animation properties calls a method called move, which must be defined in your car class. The move method should compare the current baseX position against the paneWidth. If baseX gets to the end of the current window, it should reset the baseX position to the beginning of the window.
public void move()
{
if ( baseX > paneWidth )
{
baseX = -20;
}
else
{
baseX += 1;
}
setValues();
}
Rerun the application, the car will now start moving. If you make the window wider, the car will still restart after it reaches the initial pane width.

Task 5: To properly update the paneHeight and paneWidth when the window is resized, you must provide addListener methods for both the height and width.
scene.widthProperty().addListener( e->car.setW( car.getWidth()));
scene.heightProperty().addListener( e->car.setH( car.getHeight()));

The setW and setH methods need to be defined in the car class, which will reset the paneWidth and paneHeight.
public void setW( double newWidth )
{
this.paneWidth = newWidth;
setValues();
}
  
public void setH( double newHeight )
{
this.paneHeight = newHeight;
setValues();
}
Rerun the application. Resize the window, the car will now go to the end of the window before starting over.

Task 6: To pause the animation, we need to monitor the mouse press. Add the following commands to the Start method.
  
car.setOnMousePressed( e->animation.pause());
car.setOnMouseReleased( e->animation.play());
Rerun the application. Press the mouse key, the animation should stop. Release the mouse key, the animation should resume.

Task 7: Implement a keyboard handler to determine if the user presses the UP or DOWN keys. If the UP key is pressed, the animation rate will be increased. If the DOWN key is pressed, the animation rate will be decreased.
car.requestFocus();
car.setOnKeyPressed(e ->
{
switch( e.getCode())
{
case UP:
animation.setRate( animation.getRate()+1 );
break;
case DOWN:
animation.setRate( animation.getRate()-1 );
break;
}};

Task 8: Implement new key handlers for LEFT and RIGHT keys. The LEFT key should decrease the baseY coordinates of the car so it gets higher on the screen. The RIGHT key should increase the baseY coordinates of the car so it gets lower on the screen. Create a setCarH() parameter that increases or decreases the baseY parameter by 10. Ensure that the car does not go out of bounds of the window.

Task 9: Implement a new key hander for the HOME key. The HOME key will reset the baseX parameter to 0 so the car starts over at the initial position. Create a resetCarW() method in the car class.

This lab is worth 20 points
To receive credit for this module’s lab, you must provide:
⦁   Final RacingCar application source code from Task 9 [RacingCar.java]

Solutions

Expert Solution

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// RacingCar.java (contains CarPane class as inner class)

import javafx.animation.KeyFrame;

import javafx.animation.Timeline;

import javafx.application.Application;

import static javafx.application.Application.launch;

import javafx.scene.Scene;

import javafx.scene.layout.Pane;

import javafx.scene.paint.Color;

import javafx.scene.shape.Circle;

import javafx.scene.shape.Polygon;

import javafx.scene.shape.Rectangle;

import javafx.stage.Stage;

import javafx.util.Duration;

public class RacingCar extends Application {

    //CarPane class representing a Car object

    public class CarPane extends Pane {

        private double paneWidth = 200; // Width of the pane

        private double paneHeight = 200; // Height of the pane

        private double baseX = 0; // Initial X placement of Car

        private double baseY = paneHeight; // Initial y placement of Car

        private Circle c1 = new Circle(baseX + 15, baseY - 5, 5); // Placement of first wheel

        private Circle c2 = new Circle(baseX + 35, baseY - 5, 5); // Placement of second wheel

        private Rectangle carBody = new Rectangle(baseX, baseY - 20, 50, 10); // Car body

        private Polygon carTop = new Polygon(baseX + 10, baseY - 20, // Car top

                baseX + 20, baseY - 30, baseX + 30, baseY - 30,

                baseX + 40, baseY - 20);

        public CarPane() {

            carBody.setFill(Color.CYAN);

            carTop.setFill(Color.BLUE);

            this.getChildren().addAll(c1, c2, carBody, carTop);

        }

        public void setValues() {

            c1.setCenterX(baseX + 15);

            c1.setCenterY(baseY - 5);

            c2.setCenterX(baseX + 35);

            c2.setCenterY(baseY - 5);

            carBody.setX(baseX);

            carBody.setY(baseY - 20);

            carTop.getPoints().clear();

            carTop.getPoints().addAll(baseX + 10, baseY - 20,

                    baseX + 20, baseY - 30, baseX + 30, baseY - 30,

                    baseX + 40, baseY - 20);

        }

        public void move() {

            if (baseX > paneWidth) {

                //wrapping from other end

                baseX = -20;

            } else {

                //incrementing 5 spaces forward, 1 was a bit too slow

                baseX +=5;

            }

            setValues();

        }

        public void setW(double newWidth) {

            this.paneWidth = newWidth;

            setValues();

        }

        public void setH(double newHeight) {

            this.paneHeight = newHeight;

            setValues();

        }

       

       //method to increase or decrease car's baseY

        public void setCarH(double change){

            //adding change to baseY

            double result=baseY+change;

            //if the car is still within range, assigning new value to baseY

            //and setting values

            if(result>=30 && result<paneHeight){

                baseY=result;

                setValues();

            }

        }

       

        //method to reset car baseX to 0

        public void resetCarW(){

            baseX=0; //you may assign -20 if you prefer that

            setValues();

        }

    }

    @Override

    public void start(Stage primaryStage) {

        // Create a new CarPane

        CarPane car = new CarPane();

        Scene scene = new Scene(car, 200, 200);

        primaryStage.setTitle("Racing Car"); // Set the stage title

        primaryStage.setScene(scene); // Place the scene in the stage

        primaryStage.show(); // Display the stage

        Timeline animation = new Timeline(new KeyFrame(Duration.millis(100), e -> car.move()));

        animation.setCycleCount(Timeline.INDEFINITE);

        animation.play(); // Start animation

        scene.widthProperty().addListener(e -> car.setW(car.getWidth()));

        scene.heightProperty().addListener(e -> car.setH(car.getHeight()));

        car.setOnMousePressed(e -> animation.pause());

        car.setOnMouseReleased(e -> animation.play());

        car.requestFocus();

        car.setOnKeyPressed(e -> {

           switch (e.getCode()) {

                case UP:

                    animation.setRate(animation.getRate() + 1);

                    break;

                case DOWN:

                    if (animation.getRate() > 0) {

                        animation.setRate(animation.getRate() - 1);

                    }

                    break;

                //key handler for left, right and home keys

                case LEFT:

                    //decreasing height by 10

                    car.setCarH(-10);

                    break;

                case RIGHT:

                    //increasing height by 10

                    car.setCarH(10);

                    break;

                case HOME:

                    //resetting car position from left end

                    car.resetCarW();

                    break;

            }

        });

    }

    public static void main(String[] args) {

        launch(args);

    }

}

/*OUTPUT*/



Related Solutions

Python 1.Suppose you were going to design an event-driven application like the famous wack-a-mole game. Do...
Python 1.Suppose you were going to design an event-driven application like the famous wack-a-mole game. Do the following: a) draw a mockup of the layout of the screen--this is usually easiest by hand. Submit a legible picture of your drawing. b) List the events your game would have to respond to (such as when certain keys are pressed). 2.Explain why you should avoid using loops to repeat actions in a GUI application. What should you do instead?
Prototyping an Event-Driven IT Application DC Medical Supply, located in Washington, DC is in the industry...
Prototyping an Event-Driven IT Application DC Medical Supply, located in Washington, DC is in the industry of medical device sales. Its market share is small compared to the industry leaders, but it hopes to increase its share by becoming more responsive to customer needs. DC Medical Supply would like your help documenting their sales process using an event driven ERP. The following is a description of the sales/collection process of DC Medical Supply. When customers need to order medical devices,...
In an event-driven program, you design the screens, define the objects, and define how the screens...
In an event-driven program, you design the screens, define the objects, and define how the screens will connect. Within an event-driven program, a component from which an event is generated is the source of the event. Other than changes to the planning stage, how is the development of an event-driven program different from that of a procedural program? How would a programmer create a plan for an animation?
Design JavaFX application with 7 labels and one textfield where user enters input inches.  When user enters...
Design JavaFX application with 7 labels and one textfield where user enters input inches.  When user enters his choice and presses enter key to complete input, program outputs resulting yards, feet, and inches.   Use class P5 that extends Application  with start method in it, and class P5Pane that extend GridPane. The only inctance variables for P5Pane class are inputInches where user enters input  inches, and three labels: outYards, outFeet, and outInches where program displays result of conversion.  Use the following names for instance variables:...
Write a JavaFX multiple stage application which has at least two stages, a primary one and a secondary one.
JavaFX Two-Stage ApplicationWrite a JavaFX multiple stage application which has at least two stages, a primary one and a secondary one.The primary stage should have a gridpane which has at least a 2*3 grid.On each cell of the grid, please place a different node from at least one of the three types: a UI control or a shape or an image view, etc.On the secondary stage, you should design a layout with binding property.Your overall project design should reflect a...
Write a paragraph or two about which of five software architecture patterns (Layered Architecture, Event Driven...
Write a paragraph or two about which of five software architecture patterns (Layered Architecture, Event Driven Architecture, Microkernel Architecture, Microservices Architecture Pattern, and Space-Based Architecture) would be best given each scenario. Indicate which pattern would be used to implement the system and why it is the best choice. Use descriptions of how the various architectural characteristics apply to this system and pattern to support your decision as needed. The first system in question is a set of software drivers and...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT