CS 1181 - Lab 03
The due date for every lab assignment is found in the course’s Pilot drop box.
POINTS: 10
PURPOSE: This lab will introduce you to Java’s framework for working with simple graphics, as well as the concept of an animation loop and dialog boxes for I/O.
PROCEDURES: You are provided with a “starter” Project for this lab. Import this project file (In NetBeans Use File->Import->From Zip). CS1181BallPanel uses JavaFX to display an animation of two balls bouncing around in a resizable window. This class creates and starts the animation loops, contains the information for the two balls, and contains the handle method that updates the effective display/position of the balls on every animation clock/frame event. The animation loop is infinite – it halts only when the window is closed. In the provided started code, the balls “bounce” off the edges of the application window, but “ignore” each other.
Step One: Clean up the code - Use a list of objects to represent related information
As written, the class is a coding horror. The ball graphics are represented by a series of variables within the class, which can make it difficult to debug, change code, or add additional balls. To address this problem, your first task is to develop a “Ball” class that will contain all of the information needed to display and update each Ball. Update CS1181BallPanel as necessary to use instances of your new Ball class instead of the variables used in the initial code.
The ball class should have a method named “move” than checks for boundary conditions and updates the ball’s position and instance variables/fields. The handle method in CS1181 should not do any boundary condition checking – it should call the “move” method of the ball. You may determine the argument list for your move method.
You code should be flexible. It should allow for any number of balls using some sort of container (such as an ArrayList). To begin, create two instances of your Ball class that are identical to those in the started code, add those to your list, and demonstrate that your ‘more elegant’ code performs the same task as the starter code.
Next, add a constructor to your Ball class that creates a ball with randomly assigned a radius, initial position, color, and direction of travel. This constructor will take two parameters (maxWidth and maxHeight) which you can use to send the current screen dimentions to help appropriate randomization of the ball’s initial position. Initially, ball attributes should be set randomly using the following ranges: any legal position inside of the scene for x/y coordinates, 10-20 pixels diameter, 0-10 pixels per refresh cycle for rise (deltaY) and run (deltaX). A random color can be created using the following code fragment:
int red = (int)(Math.random() * 255);
int green = (int)(Math.random() * 255);
int blue = (int)(Math.random() * 255);
Color randomColor = Color.rgb(red, green, blue);
Finally, prompt the user (I recommend using a JOptionPane.showInputDialog() box) to select the number of balls that will appear in the panel. Create and add this number of ‘random’ balls to your collection and then begin the animation.
DEMONSTRATE YOUR WORK TO YOUR LAB INSTRUCTOR: This should be done in lab, if possible. You may demonstrate your work as many times as you like. Let your lab assistant know when you are satisfied with your grade – only then will they record it. Upload your lab work immediately after your ask your lab assistant to record your grade.
UPLOAD YOUR FINAL WORK BEFORE THE DROP BOX DUE DATE: Archive your assignment as a zipfile and upload it to Pilot. Please use the file name CS1181-Lab03-YourLastName.zip Please use this standard for all course submissions. Ask your TA for help, if needed, to export your project (File -> Export Project -> Zip) or upload it to the appropriate Pilot dropbox.
GRADING RUBRIC
FUNCTIONALITY
• [1 point] Attributes for the ball’s x coordinate, y coordinate, radius, rise, run, color, etc.
• [1 point] A constructor that sets the rest of the attributes randomly according the ranges listed above.
• [1 point] Move method has the same functionality currently implemented in the handle method of thes starter code. The move method can take, as parameters, any information (such as current window size), that your routine requires to perform appropriate “bouncing”.
OVERALL DOCUMENTATION AND TESTING
Code: -
/**
* CS1181 Lab Starter Code
* UPDATE WITH YOUR NAME HERE
* Lab Section: XX
* Lab Instructor: Lorem Ipsum
* Lecture Instructor: Dr. Doom
*
* Citations: Final lab code is based on sample code distributed as
part of
* the laboratory assignment/requirements.
*
* INSTRUCTIONS: Please update this code as specified in the
laboratory
* instructions. Update all comments in the starter code (including
this header
* block)to reflect your changes and information. One of those
changes should
* be to remove these instructions!
*/
package cs1181ballpanel;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class CS1181BallPanel extends Application implements
EventHandler<ActionEvent> {
private int INITIAL_WIDTH_IN_PIXELS = 800;
private int INITAL_HEIGHT_IN_PIXELS = 600;
private Circle ballOne; // WARNING: This is a coding
HORROR
private int ballOneDeltaX = 2; // You will implement this
elegantly
private int ballOneDeltaY = -1; // by creating a Ball class
that
private Circle ballTwo; // encapsulates all this information
in
private int ballTwoDeltaX = -3; // a single class.
private int ballTwoDeltaY = -3;
private Scene scene;
@Override
public void start(Stage stage) {
// Initialite the Stage
stage.setTitle("CS1181 Ball Panel");
Pane pane = new Pane();
scene = new Scene(pane, INITIAL_WIDTH_IN_PIXELS,
INITAL_HEIGHT_IN_PIXELS);
stage.setScene(scene);
stage.show();
// Initialize the animation loop
KeyFrame keyFrame = new KeyFrame(Duration.millis(10), this);
Timeline timeline = new Timeline(keyFrame);
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
// Initialize two Balls and add them to the panel/scene
ballOne = new Circle();
ballOne.setRadius(30);
ballOne.setFill(Color.RED);
ballOne.setCenterX(50);
ballOne.setCenterY(200);
ballTwo = new Circle();
ballTwo.setRadius(40);
ballTwo.setFill(Color.BLUE);
ballTwo.setCenterX(500);
ballTwo.setCenterY(400);
pane.getChildren().add(ballOne);
pane.getChildren().add(ballTwo);
} // end method start
public static void main(String[] args) {
launch(args);
} // end method main
/**
* This method updates the frame/scene. It is called automatically
by the
* animation timeline every animation cycle.
*
* @param event Contains the specific information for the timeline
clock
* event
*/
@Override
public void handle(ActionEvent event) {
// NOTE: This is a coding HORROR. Update this to use a list!
// Do not simply repreat code!!
// Check boundry contitions and update direction
if (ballOne.getCenterX() + ballOne.getRadius() >=
scene.getWidth() ) {
ballOneDeltaX = -ballOneDeltaX;
} // end-if ball hits Right boundry
if (ballOne.getCenterY() + ballOne.getRadius() >=
scene.getHeight() ) {
ballOneDeltaY = -ballOneDeltaY;
} // end-if ball hits Bottom boundry
if (ballOne.getCenterX() <= ballOne.getRadius() ) {
ballOneDeltaX = -ballOneDeltaX;
} // end-if ball hits Left boundry
if (ballOne.getCenterY() <= ballOne.getRadius() ) {
ballOneDeltaY = -ballOneDeltaY;
} // end-if ball hits Top boundry
ballOne.setCenterX(ballOne.getCenterX()+ballOneDeltaX);
ballOne.setCenterY(ballOne.getCenterY()+ballOneDeltaY);
// Check boundry contitions and update direction
if (ballTwo.getCenterX() + ballTwo.getRadius() >=
scene.getWidth()) {
ballTwoDeltaX = -ballTwoDeltaX;
} // end-if ball hits Right boundry
if (ballTwo.getCenterY() + ballTwo.getRadius() >=
scene.getHeight()) {
ballTwoDeltaY = -ballTwoDeltaY;
} // end-if ball hits Bottom boundry
if (ballTwo.getCenterX() <= ballTwo.getRadius()) {
ballTwoDeltaX = -ballTwoDeltaX;
} // end-if ball hits Left boundry
if (ballTwo.getCenterY() <= ballTwo.getRadius()) {
ballTwoDeltaY = -ballTwoDeltaY;
} // end-if ball hits Top boundry
ballTwo.setCenterX(ballTwo.getCenterX() + ballTwoDeltaX);
ballTwo.setCenterY(ballTwo.getCenterY() + ballTwoDeltaY);
} // end method handle
} // end class
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
VERY VERY IMPORTANT NOTE: place your US.png and EU.png images in the root directory of your project, if you place it in wrong directory, it will not be displayed. If you are using netbeans, click on the files tab (from the three tabs on the left side (Projects/Services/Files)), there you can see your project name, right click on it and paste the images. (i.e the images should be in the same location where build.xml exists)
// TimeButtonDemo.java
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.util.Duration;
import java.util.Calendar;
import javafx.scene.control.Label;
import java.text.SimpleDateFormat;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
public class TimeButtonDemo extends Application {
protected BorderPane getPane() {
BorderPane pane = new BorderPane(); // pane for containing buttons and clock
HBox paneForButtons = new HBox(50); // pane for containing buttons
// write code for buttons
DigitalClock clock = new DigitalClock(); // clock to be added to pane
pane.setCenter(clock);
//creating 12 hours Button
Button US = new Button("12 hr");
//creating an ImageView to display button icon, resizing to fit inside button
//make sure you have US.png and EU.png files in the root directory of
//your project
ImageView im1 = new ImageView(new Image("file:US.png", true));
im1.setFitWidth(40);
im1.setFitHeight(40);
US.setGraphic(im1);
Button EU = new Button("24 hr");
ImageView im2 = new ImageView(new Image("file:EU.png", true));
im2.setFitWidth(40);
im2.setFitHeight(40);
EU.setGraphic(im2);
//setting a green border for the pane
paneForButtons.setStyle("-fx-border-style: solid inside;"
+ "-fx-border-width: 2;" + "-fx-border-color: green;");
paneForButtons.getChildren().addAll(US, EU);
paneForButtons.setAlignment(Pos.CENTER);
pane.setBottom(paneForButtons);
// handle button clicks with lambdas
US.setOnAction(e -> {
//changing to 12 hr format
clock.changeFormat12();
});
EU.setOnAction(e -> {
//changing to 24 hr format
clock.changeFormat24();
});
// handle keyboard presses with lambdas
pane.setOnKeyPressed(e -> {
if (e.getCode() == KeyCode.UP) {
//changing clock color to red
clock.setTextFill(Color.RED);
} else if (e.getCode() == KeyCode.DOWN) {
//changing clock color to cyan
clock.setTextFill(Color.CYAN);
} else if (e.getCode() == KeyCode.ENTER) {
//changing clock color to black
clock.setTextFill(Color.BLACK);
}
});
return pane;
}
public void start(Stage primaryStage) {
// Create a scene and place it in the stage
Scene scene = new Scene(getPane(), 250, 150);
primaryStage.setTitle("ClockApplication"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
public static void main(String[] args) {
launch(args);
}
}
class DigitalClock extends Label {
private SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss a");
private Timeline animation;
private Calendar time;
public DigitalClock() {
// get time and set text
time = Calendar.getInstance();
setText(dateFormat.format(time.getTime()));
// change text font here
setFont(new Font("Arial", 30));
// set animation here
//creating animation TimeLine using lambda expression
animation = new Timeline(new KeyFrame(Duration.seconds(0.1), e -> {
//updating time
time.setTime(Calendar.getInstance().getTime());
//setting new time
setText(dateFormat.format(time.getTime()));
}));
animation.setCycleCount(Timeline.INDEFINITE);//repeating indefinitely
//starting animation
animation.play();
}
public void changeFormat24() {
// write code here for changing to 24 hour clock
dateFormat = new SimpleDateFormat("HH:mm:ss");
}
public void changeFormat12() {
// write code here for changing to 12 hour clock
dateFormat = new SimpleDateFormat("hh:mm:ss a");
}
}
/*OUTPUT*/
CS 1181 - Lab 03 The due date for every lab assignment is found in the...
JavaFX! Just need to fill several lanes of code please!!!
CSE205 OOP and Data Structure Quiz #15 Last Name (print) First Name (print) Write a JavaFX GUI application program that simulates a timer. The timer should show "count: the beginning and increase the number by 1 in every one second, and so on. o" at .3 A Timer - × A Timer Count: 0 Count: 1 (B) After 1 second, the GUI Window (A) Initial GUI Window According to the...
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...
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...
Add another changeColor() method (i.e. you will now have 2 methods called "changeColor"). This one accepts an int parameter and changes the color based on that int. The valid colors are "red", "yellow", "green", "blue", "magenta" and "black". In your code, map each color to an integer (e.g. in my code 3 means green.) If the number passed to the method is not valid, change the color to red. In the bounceTheBall() method, where you test for collisions with top...
You may adjust the code as you want. Thank
you!
CODING HERE:
import javafx.application.Application;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import javafx.geometry.*;
public class OrderSystem extends Application implements
EventHandler<ActionEvent>
{
// Attributes for GUI
private Stage stage; // The entire window, including title bar and
borders
private Scene scene; // Interior of window
private BorderPane layout;
// Add four labels
private Label itemLabel = new Label("Item Name:");
private Label numberLabel = new Label("Number:");
private Label costLabel...
Final PYTHON program: Create a home inventory class that will be used by a National Builder to maintain inventory of available houses in the country. The following attributes should be present in your home class: -private int squarefeet -private string address -private string city -private string state -private int zipcode -private string Modelname -private string salestatus (sold, available, under contract) Your program should have appropriate methods such as: -constructor -add a new home -remove a home -update home attributes At...
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)...
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...
Keep the ball in bounds by adding conditional statements after the TODO comments in the paintComponent() method to check when the ball has hit the edge of the window. When the ball reaches an edge, you will need to reverse the corresponding delta direction and position the ball back in bounds. Make sure that your solution still works when you resize the window. Your bounds checking should not depend on a specific window size This is the java code that...
java This lab is intended to give you practice creating a class with a constructor method, accessor methods, mutator methods, equals method , toString method and a equals method. In this lab you need to create two separate classes, one Student class and other Lab10 class. You need to define your instance variables, accessor methods, mutator methods, constructor, toString method and equals method in Student class. You need to create objects in Lab10 class which will have your main method...