Question

15.3 (Move the ball) Write a program that moves the ball in a pane. You should...

15.3 (Move the ball) Write a program that moves the ball in a pane. You should define a pane class for displaying the ball and provide the methods for moving the ball left, right, up, and down, as shown in Figure 15.24c. Check the boundary to prevent the ball from moving out of sight completely.

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
public class Driver extends Application {
@Override
public void start(Stage primaryStage) throws Exception {

double width = 400;
double height = 400;
BallPane ballPane = new BallPane(width / 2,height / 2, Math.min(width,height) / 15);//setting border for circle pane

Button btUp = new Button("Up");
btUp.setOnAction(e -> ballPane.moveUp());

Button btDown = new Button("Down");
btDown.setOnAction(e -> ballPane.moveDown());

Button btLeft = new Button("Left");
btLeft.setOnAction(e -> ballPane.moveLeft());

Button btRight = new Button("Right");
btRight.setOnAction(e -> ballPane.moveRight());

HBox buttons = new HBox(btUp, btDown, btLeft, btRight);
buttons.setAlignment(Pos.BOTTOM_CENTER);
buttons.setSpacing(15);
buttons.setPadding(new Insets(10, 10, 10, 10));

BorderPane pane = new BorderPane();
pane.setCenter(ballPane);
pane.setBottom(buttons);

Scene scene = new Scene(pane, width, height);
primaryStage.setScene(scene);
primaryStage.setTitle("Click to move ball");
primaryStage.show();
}

private class BallPane extends Pane {

private Circle circle;

public BallPane() {
this(0, 0, 10);
}
public BallPane(double centerX, double centerY, double radius) {
circle = new Circle(centerX, centerY, radius);
getChildren().add(circle);
}

public void moveUp() {
if (circle.getCenterY() - circle.getRadius() - 10 < 0) return;
circle.setCenterY(circle.getCenterY() - 10);
}
public void moveDown() {
if (circle.getCenterY() + circle.getRadius() + 10 > getHeight()) return;

circle.setCenterY(circle.getCenterY() + 10);
}
public void moveRight() {
if (circle.getCenterX() + circle.getRadius() + 10 > getWidth()) return;
circle.setCenterX(circle.getCenterX() + 10);
}
public void moveLeft() {
if (circle.getCenterX() - circle.getRadius() - 10 < 0) return;
circle.setCenterX(circle.getCenterX() - 10);

}

}

public static void main(String[] args) {
Application.launch(args);
}
}

So thats the code im using what I really need help with is understanding the if statements in the moveUp moveDown moveLeft and moveRight methods. Is there a different way to move the circle object in the pane that's a little more simple or if someone could just break down the method that would be great

0 0
Add a comment Improve this question Transcribed image text
Answer #1

I'll try to explain what the move...() methods do.
First we need to understand -
1. when circle should move up or down, the y coordinate of the center will change. the x cordinate will not change and remain same.
2. when circle should move left or right, the x coordinate of the center will change. the y cordinate will not change and remain same.

Next, in computer systems, the top left corner is 0,0 and x increases as we right. y increases as we come down. This is different from the normal cartesian systems. So the origin here is in top left corner. x increasing as we move towards right and y increasing as we move downwards


Now each of the move methods try to change either x or y 10 pixels at a time. But we can not be incrementing/decrementing x or y by 10 all the time.

Let us take moveUp() and understand. When the circle needs to move up, the y coordinate should reduce by 10. As long the new y coordinate would be inside screen boundary there is no issue. But what if we are top edge of the window ? Now if we decrement another 10 , the the top circumference portion of the circle will go out of the screen. The y coordinate of top edge of circle will be at a distance = center y - radius. Now we should ensure that we move another 10 pixels up (i.e. reduce y), we do not have the circle moving out of the screen. So the moveUp() method first checks if center y - radius -10 (which will be top edge of circle) will become -ve (i.e goes out of top screen edge), then we should not move upwards. So the method simply returns. If it does not become -ve, we are still going to stay on screen, so we will update the circle's y cordinate to current y - 10.

public void moveUp() {
   if (circle.getCenterY() - circle.getRadius() - 10 < 0) return; /*check if top edge of circle will go out screen?, then don't change the y cordinate of circle*/
   circle.setCenterY(circle.getCenterY() - 10); /*this statement is executed only if the above return did not execute. So we will still be inside screen if move 10 pixels, so update the y coordinat of center of circle by reducing 10 in order to move up*/
}

On the same lines,

For moveDown()- we first check if bottom edge of circle will not go out window's bottom edge.
This check is done using if (circle.getCenterY() + circle.getRadius() + 10 > getHeight()) .
If that is the case we simply return and do not change center y. Here getHeight() returns windows height . But if that condition is false, we update y as y+10 for circle's center using circle.setCenterY(circle.getCenterY() + 10);


For moveLeft()- we first check if by reducing 10 pixels for circle, would we move out of screen on left side of window. The condition for that is if (circle.getCenterX() - circle.getRadius() - 10 < 0) return;. We are to check the x cordinate for moving left or right. So circle's left edge is center x - radius. If we subtract 10 from that, we should not be going on -ve x axis. If so we will not update the circle's center x. Otherwise we update the center x by subtracting 10 to it to move by 10 pixels

For moveRight() we should again check x coordinate of right edge of circle will stay inside screen if we are to update it by adding 10 . How to get the right edge of window? use the getWidth() to get the width of the window. This check is done using if (circle.getCenterX() + circle.getRadius() + 10 > getWidth()) return; If we are going to be inside the window boundaries, we update x by adding 10 using circle.setCenterX(circle.getCenterX() + 10);


In summary,
1. moveUp - check if we would go out of top edge, if so , simply return. otherwise to move up, subtract 10 from y cordinate of center
2. moveDown - check if we would go out of bottom edge, if so , simply return. otherwise to move down, add 10 to y cordinate of center
3. moveLeft - check if we would go out of left edge of window, if so , simply return. otherwise to move left, subtract 10 from x cordinate of center
4. moveRight - check if we would go out of right edge of window, if so , simply return. otherwise to move right, add 10 to x cordinate of center


Add a comment
Know the answer?
Add Answer to:
15.3 (Move the ball) Write a program that moves the ball in a pane. You should...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • (5 points) Analyze the following codes. b) import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import...

    (5 points) Analyze the following codes. b) import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class Test extends Application { @Override // Override the start method in the Application class public void start(Stage primaryStage) { Button btOK = new Button("OK"); Button btCancel = new Button("Cancel"); EventHandler<ActionEvent> handler = new EventHandler<ActionEvent>() { public void handle(ActionEvent e) { System.out.println("The OK button is clicked"); } }; btOK.setOnAction(handler); btCancel.setOnAction(handler); HBox pane = new HBox(5); pane.getChildren().addAll(btOK, btCancel); Scene...

  • Java Programming Assignment (JavaFX required). You will modify the SudokuCheckApplication program that is listed below. Start...

    Java Programming Assignment (JavaFX required). You will modify the SudokuCheckApplication program that is listed below. Start with the bolded comment section in the code below. Create a class that will take string input and process it as a multidimensional array You will modify the program to use a multi-dimensional array to check the input text. SudokuCheckApplication.java import javafx.application.*; import javafx.event.*; import javafx.geometry.*; import javafx.scene.*; import javafx.scene.control.*; import javafx.scene.layout.*; import javafx.stage.*; public class SudokuCheckApplication extends Application { public void start(Stage primaryStage)...

  • use this code of converting Km to miles , to create Temperature converter by using java...

    use this code of converting Km to miles , to create Temperature converter by using java FX import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.geometry.Pos; import javafx.geometry.Insets; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.Button; import javafx.event.EventHandler; import javafx.event.ActionEvent; /** * Kilometer Converter application */ public class KiloConverter extends Application { // Fields private TextField kiloTextField; private Label resultLabel; public static void main(String[] args) { // Launch the application. launch(args); } @Override public void start(Stage primaryStage) { //...

  • Write a program that will define a runnable frame to have a ball move across the...

    Write a program that will define a runnable frame to have a ball move across the frame left to right. While that is happening, have another frame that will let the user do something like click a button or input into a textfield, but keep the ball moving in the other frame. When the ball reaches the right edge of the frame or when the user takes action - enters in textfield or clicks the button, end the thread. The...

  • Java: In this assignment, you will create an accumulator accumulator-calculator that displays a sad face “...

    Java: In this assignment, you will create an accumulator accumulator-calculator that displays a sad face “ :-( “ whenever the number displayed by the calculator is negative and a happy face “ :-) ” whenever the number displayed is positive. The calculator responds to the following commands: num + , num - , num * , num / and C ( Clear ). After initial run, if the user clicks 8 and then presses the “+” button for example, the...

  • Use Kilometer Converter application code to write Temperature Converter application to convert degrees Fahrenheit into degrees...

    Use Kilometer Converter application code to write Temperature Converter application to convert degrees Fahrenheit into degrees Celsius ((F - 32)*5/9). It needs to be JavaFX 1 import javafx.application. Application; 2 import javafx.stage. Stage; 3 import javafx.scene. Scene; 4 import javafx.scene.layout.HBox; 5 import javafx.scene.layout. VBox; 6 import javafx.geometry.Pos; 7 import javafx.geometry.Insets; 8 import javafx.scene.control.Label; 9 import javafx.scene.control. TextField; 10 import javafx.scene.control.Button; 11 import javafx.event. EventHandler; 12 import javafx.event. ActionEvent; 13 14 ** 15 * Kilometer Converter application 16 17 18 public...

  • JavaFX programming (Not Javascript) Using the code from BallPane.java and BounceBallControl.java create a "Pong for One"...

    JavaFX programming (Not Javascript) Using the code from BallPane.java and BounceBallControl.java create a "Pong for One" game - a rectangular paddle moves back and forth via mouse drag along the bottom of the pane; the bottom of the paddle should be about 1/2 the diameter of the ball off the bottom. If the ball connects with the paddle, then it bounces at a 90 degree angle back into the pane space. If the ball misses the paddle, then the score...

  • / Finish the code to make it work import static javafx.application.Application.launch; import java.io.File; import javafx.application.Application; import...

    / Finish the code to make it work import static javafx.application.Application.launch; import java.io.File; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.media.AudioClip; import javafx.stage.Stage; public class JukeBox extends Application { private ChoiceBox<String> choice; private AudioClip[] tunes; private AudioClip current; private Button playButton, stopButton;    //----------------------- // presents an interface that allows the user to select and play // a tune from a drop down box //-----------------------   ...

  • This task is a program framework that you should complete. The program should allow the user...

    This task is a program framework that you should complete. The program should allow the user to move a circular figure with the mouse over a drawing area. The current position of the figure is displayed continuously: Given is the main program: import javafx.scene.Scene; import javafx.application.Application; import javafx.beans.value.*; import javafx.scene.*; import javafx.scene.paint.Color; import javafx.scene.text.Text; import javafx.stage.Stage; public class Main extends Application { private DraggableCircle dc; private Text text; private void updateText() { text.setText("("+dc.getCenterX()+", "+dc.getCenterY()+")"); } @Override public void start(final Stage...

  • Intro to Java - Assignment JAVA ASSIGNMENT 13 - Object Methods During Event Handling Assignment 13...

    Intro to Java - Assignment JAVA ASSIGNMENT 13 - Object Methods During Event Handling Assignment 13 Assignment 13 Preparation This assignment will focus on the use of object methods during event handling. Assignment 13 Assignment 13 Submission Follow the directions below to submit Assignment 13: This assignment will be a modification of the Assignment 12 program (see EncryptionApplication11.java below). Replace the use of String concatenation operations in the methods with StringBuilder or StringBuffer objects and their methods. EncryptTextMethods.java ====================== package...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT