Please by Java! Lab 10

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899604
Joined: Mon Aug 02, 2021 8:13 am

Please by Java! Lab 10

Post by answerhappygod »

Please by Java! Lab 10
Please By Java Lab 10 1
Please By Java Lab 10 1 (88.06 KiB) Viewed 25 times
Introduction: The focus of this lab is working with classes and objects. Specifically, you get to write a simple, event-driven, graphical user interface (GUI) program using the JavaFX framework When the program first opens up, a stick figure gets displayed. The user may right click somewhere in the window, at which location a circle with a random size and color will appear (see Figure 1). The user may click and drag the head of the stick figure around the window, and the body will follow. If the very end of the left arm comes in contact with the circle, then some property of the latter must noticeably change. Lab11: Scott Summers Figure 1: When the program first opens up, just the stick figure is displayed. The head gets a random color. After the user right-clicks in the window, a circle with a random size and color is displayed at the location of the right-click. Here, the user already dragged the head of the stick figure over toward the right side of the window and the body followed.

Do the following: 1. Create a new class called Lab10 and delete any/all the starter code that BlueJ auto- matically adds. 2. Add the following code to Lab10: import javafx.application. Application; import javafx. stage. Stage; import javafx.scene.layout.Pane; import javafx.scene. Scene; import javafx.scene. shape. *; import javafx.scene. paint.Color; import javafx.scene. input.*; = public class Lab10 { private static final int SCENE_WIDTH = 640; private static final int SCENE_HEIGHT = 480; private static final int HEAD_RADIUS = 35; private static final int TORSO_HEIGHT 100; private static final int CIRC_MAX_RADIUS = 100; private static final int CIRC_MIN_RADIUS = 25; // You might need to add other final values here. public void start (Stage primaryStage) { } } 3. Press compile. Your program should not contain any syntax errors. Note that, unlike previous programs that we have written, Lab10 will just have a start method, rather than a main method. This is the method that is called by the virtual machine when a JavaFX application is launched. It takes as its only parameter a Stage object, to which you will add a Scene, to which you will add a Pane, to which you will add shapes, and so on. 4. At this point, your program should compile, but that's about it. You shouldn't even be able to run it! After all, Lab10 does not contain a main method. The reason you can't even run your program is because it's technically not a valid JavaFX application... yet. 5. Technically speaking, every valid JavaFX application must be an Application. There- fore, have Lab10 inherit from Application (you'll learn more about inheritance in CS 262). For now, just append the code "extends Application" (without the double- quotes) to the Lab10 class header. That is, put that code after Lab10 but before the opening curly brace that marks the beginning of the body of Lab10. After completing this step, your Lab10 should still compile.

6. Try to run your Lab10. In the Blue J project window, right click on the Lab10 class and select “Run JavaFX Application”. However, when you run it, it still doesn't do anything, which is perfectly fine. 7. We will now write code that creates and displays the head of the stick figure. (a) Add the following code to the top of the start method: Circle head = new Circle(); head.setRadius (HEAD_RADIUS); head.setCenterX(0); head.setCenterY(0); head.setStroke (Color.BLACK); head. setFill(Color.rgb(new java.util. Random() .nextInt(256), new java.util. Random() .nextInt(256), new java.util. Random() .nextInt (256))); This code creates a new Circle and sets its radius, (center) position and color. The setStroke sets its outline color. Note that the setCenterX and setCentery methods change the position of the center point of the head. After completing this step, Lab10 should still compile. However, if you try to run it, nothing happens. That's because we have to set the Scene, in which the head will eventually be displayed. (b) In JavaFX, you need to add shapes to containers, such as Pane. So, add the following line of code to the very beginning of the start method: Pane pane = new Pane(); This code creates a Pane that we can add shapes to later on. Here, pane is an instance of Pane, which is a very simple container class. Container classes, such as Pane, in the language of JavaFX, are designed to hold Nodes (user interface elements, shapes, other containers, and so on). Adding elements to a container class like this is one way how you can display things in a JavaFX program. (c) Add the following line of code just after the "head. setFill(...” code: pane.getChildren ().addAll(head); This code adds the head to the pane, which is necessary in order for the former to (eventually) be displayed on the screen.

(d) We must add the pane to a Scene, set the Scene of the primaryStage and then show the primaryStage. Add the following code to the bottom of the start method, after the "pane.getChildren().add(head)" line of code: Scene scene = new Scene (pane, SCENE_WIDTH, SCENE_HEIGHT); primaryStage.setScene (scene); primaryStage.setTitle("Lab10"); primaryStage.show(); This code creates a Scene that is 640 by 480 pixels and has the title “Lab10”. You should incorporate your name into the title of the primaryStage. After completing this step, Lab10 should compile and when you run it, a win- dow should be displayed with a randomly-colored circle in the upper-left corner of the window. (e) Try to figure out how make it so head shows up in the center of the window. Go back to the calls to setCenterX and setCenter from a previous step and, using SCENE_WIDTH and SCENE_HEIGHT, make it so the head gets displayed in the center of the Pane. The main thing to keep in mind is that, in computer graphics, the origin is located in the upper-left corner of the screen and 2 and y-coordinates increase as you go right and down, respectively. Before proceeding, go up to Edit and select Auto-Layout. After all, why not? 8. We will now create and display the rest of the body of the stick figure. (a) Create the torso by adding the following code immediately before the "pane.getChildren() .addAll(head);" code: Line torso = new Line(); torso.setStartX(head.getCenterX()); torso.setStartY(head.getCentery() + head.getRadius()); torso.setEndX (head.getCenterX()); torso.setEndy (head.getCentery() + head.getRadius() + TORSO_HEIGHT); torso.setStroke (Color.BLACK); (b) Display the torso by passing torso in as an additional parameter, after head, in pane.getChildren().addAll(head); (e) Create and display the rest of the body arms and legs) of the stick figure, similar to how you created and displayed the torso. Make sure the stick figure looks reasonable (the arms and legs are connected to the torso, and all limbs are an appropriate size)

After completing this step, your Lab10 should compile, and when you run it, you should see a stick figure displayed, and the randomly-colored head must be in the center of the window. Before proceeding, go up to Edit and select Auto-Layout. I'm going to stop reminding you to do this, but be sure to do this regularly as you work through the remaining steps. 9. We will now add some code to allow the user to drag the head around the screen. We will do so using an event-handler specified with a “Lambda” expression. Place the fol- lowing code on the line immediately preceding the “pane.getChildren().addA11(..." code: head.setOnMouseDragged (evt -> { head.setCenterX (evt.getX(); }); This code registers an event-handler for MouseDragged events on the head, where evt is the MouseEvent object generated by the event. There's one line of code missing. Add it and then compile and run your Lab10. You should be able to drag the head around. However, notice that when you click on the head to drag it, the rest of the body does not follow the head around. Add code within the previous Lambda expression to fix this. 10. THIS STEP IS OPTIONAL, BUT VERY FUN: When you run your Lab10, you should notice that, when you click on the head to drag, it “jumps” to the mouse pointer. What we would prefer is that, when the user clicks and drags, the head should not jump around but it should stay in relative position with the mouse pointer. For example, just drag an icon around the desktop. To fix this jumpiness, complete the following optional steps: (a) Add the following code to the instance variables section of your Lab10 class (before the start method, after the finals and, of course, still inside the Lab10 class): private double dx, dy; Since these variables are declared as instance variables, they will be visible to all methods within Lab10 and they will maintain their values across method calls (including calls to the method that is implicitly defined inside the Lambda ex- pression we previously defined to handle MouseDragged events on the head. We will use dx and dy to store the relative difference between the position of the mouse click and the center position of the head.

(b) When the user clicks on the circle to drag it around, we need to capture the location at which user first pressed the mouse button, relative to the position of the head. Actually, we need to capture the horizontal and vertical differences between the head center and the location of the MouseEvent. So, add the following code immediately after the head.setOnMouseDragged (...);" code: pane.setOnMousePressed (evt -> { dx = evt.getX() - head.getCenterX(); dy evt.getY() - head.getCenterY(); }); When the user clicks anywhere on the pane (anywhere within the window of Lab10), the above code stores the horizontal and vertical differences in dx and dy, respectively, between where the MouseEvent occurred and the center of the head. However, merely setting dx and dy like this doesn't fix the problem. If you run your Lab10, when you drag the head around, it still "jumps”. (c) Therefore, go back and modify the code in the Lambda expression that is being passed to "head. onMouseDragged (...". That is, try to figure out how to use the dx and dy variables in the calls to setCenterX and ... on head to make it so the center of head and the location of the mouse remain the same distance apart when the user is dragging the head as they were when the user initially pressed the mouse to start dragging. After you complete this step, when you click and drag the head around, it shouldn't do anymore “jumping”. 11. We will now let the user add a Circle to the pane on a right-click. (a) Put the following code in the instance variables section of Lab10: private Circle circle = null; (b) Put the following code immediately after the "pane.setOnMousePressed (..." code: pane.setOnMouseClicked(evt -> { if (evt.getButton() == MouseButton. SECONDARY) { // FILL IN THE DETAILS } }); This code registers an event-handler for mouse clicks on the pane. It checks to see if the MouseEvent was a right-click. (c) In place of the previous"// FILL IN THE DETAILS” comment, add some code that instantiates (creates) circle and sets its radius, stroke, fill and position appropriately. Set its outline to be Color.BLACK, its fill to be a random color and

its radius to a random value between 25 and 75 pixels. Also, make it so circle is placed so that its center is at the location of the right-click. Be careful not to re-declare circle! (d) Display the circle in the pane. You'll need to figure out where to place the following code: pane.getChildren().add(circle); (e) Compile and run your Lab10. Test out the code you just wrote by right-clicking somewhere. If a new randomly-colored circle shows up, then great! If not, then perhaps you forgot to add a line of code that actually displays circle. Look back at the code that actually displays head and do something similar for circle. If you get a weird error (or crash), then be careful and make sure you didn't forget the statement that actually instantiates circle. (f) Odds are, at this point, each time the user right-clicks, a new randomly-colored circle gets displayed. Write some code so that, once the one circle has been added, no further circles get displayed. Hint: if circle == null is true, then create and display circle, otherwise, don't. (g) To the if from the previous step, add a corresponding else block, where you re-position circle based on the location of the right-mouse click. After completing this step, the user can right-click to display the circle and each subsequent right-click will re-position circle to the position of the right-click. 12. Write code that noticeably changes some aspect of circle if/when touched by the very end of the left arm of the stick figure. For example, among other things, you can make the circle disappear, or change its fill color or radius. Inside the MouseDragged event-handler for head, use the following code to get the location of the center of the circle and the location of the end of the left arm of the stick figure: double x1 = circle.getCenterX(), yi circle.getCentery(), x2 = larm.getEndX(), y2 larm.getEndY(); = = Compute the Euclidean distance between these two points in order to determine whether the very end of the left arm of the stick figure is touching the circle. You must use the standard formula for the Euclidean distance d between two points in the plane, say (21, yı) and (22, y2): d=V (22 – 21)? + (y2 – y.)? You should use Math.sqrt(...) for this part. If you want to make it so the circle disappears, then you can use the code: pane.getChildren().remove(circle); If you do this, consider setting circle = null; Then, after the circle disappears, the user

should be able to right-click and the circle will reappear. After completing this step, compile your program and run it. Right-click somewhere in the window to display the circle. Then, drag the stick figure over so that the end of its left arm is touching the circle and see if the latter changes based on the code that you wrote in this step. 13. Finally, make sure that you test your program thoroughly. Your program should not crash! Make sure you watch for runtime errors, like NullPointerExceptions, displayed as red text in the terminal window as you're testing your program (see Figure 2). BlueJ: Terminal Window - Lab10 can only enter input while your programming is running Exception in thread "JavaFX Application Thread" java.lang.NullPointerException at Lab 18. lambdasstart sal Lab18.java:78) at com.sun.javafx, event.Composite EventHandler.dispatchBubblingEvent (CompositeEventHa at com.sun.javafx.event. EventHandler Manager.dispatchBubblingEvent (EventHandler Manage at com.sun.javafx.event. EventHandler Manager.dispatchBubblingEvent (EventHandler Manage at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent (Composite Even at com.sun.javafx.event. BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java at com.sun.javafx.event. EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl. at com.sun.javafx.event. BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java at com.sun.javafx.event. EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl. at com.sun.javafx.event. BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java at com.sun.javafx.event. EventDispatchChainImpl.dispatchEvent(EventDispatchchainImpl. at com.sun.javafx.event. Eventutil.fireEvent Impl(EventUtil.java:74) at com.sun.javafx.event. Eventutil.fireEvent (Eventutil.java:54) Figure 2: Watch out for (and fix any/all) runtime errors like this!
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply