Question

JAVA SOLUTION This lab has four parts: Create a window. Create 5 buttons in that window....

JAVA SOLUTION

This lab has four parts:

  1. Create a window.
  2. Create 5 buttons in that window.
  3. Create an event when a button is pushed.
  4. Create an event listener that will respond to the button being pushed event.

Task 1 – Create a Window

For Java:

  1. Please ensure that the following import statements are used:

import javafx.application.Application;

import javafx.stage.Stage;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.layout.GridPane;

import javafx.scene.text.Text;

import javafx.event.EventHandler;

import javafx.scene.input.MouseEvent;

  1. Next, ensure that there is a main method which is simply using the launch method.
  2. Ensure there is a start method as well. Erase all code inside of it.
  3. Create a new GridPane object using the default constructor. We’ll use that in the next task, but we need it for the following set up commands.
  4. Create a new Scene object passing in the GridPane object, the width of the scene and the height of the scene.

NOTE: Scenes are similar to the content of a tab (a webpage) in a modern internet browser. Where stages are similar to the browser itself, which can move between webpages, but only ever shows one.

  1. Using the primaryStage object (which comes from the parameter of the start method), call the setScene method and pass in the Scene we just made.
  2. Finally, use primaryStage’s show method to display the window. You should be able to run it and see a blank white window appear.

Task 2 – Create Buttons

We can make many types of interact-able objects in our window, but we will keep it simple and use a clickable button.

For Java:

  1. We must first create a button object using the Button class. Please use the overloaded constructor and pass in the text that will be displayed on the button. Something simple, like “button 1” would be fine as long as the number changes for each new button.
  2. Now we must add it to our window. This is where the GridPane object comes in handy. Use the GridPane object’s add method, passing in the button, row position, and column position.

NOTE: The GridPane is applied to the Scene (our window/page). This enforces a grid structure on our window, which allows us to move our items around on the grid and thus window. It’s helpful for keeping even spacing between all of our items while letting us easily move buttons through the row and column position (and not pixel specific locations). The grid starts at (0, 0) in the top left of the window.

  1. You should be able to see the button in the window now. You may need to make your window bigger if you cannot see it (anything at position (0, 0) should almost always be visible).
  2. Make sure to add the remaining buttons using the same process. Don’t put them in the same grid positions though, or you won’t be able to see all of them.

Task 3 – Create an Event

            At this point, we will want to create an event object every time the button is pushed. This way we will be able to tell when the button is pushed and what to do when it is pushed.

For Java:

  1. For this part, we will need to create a new EventHandler object. This is a parameterized class (this uses the <> brackets), which means that we will need to give it some specific type of event to handle when we declare a new EventHandler. We will simply use the MouseEvent class since we want the buttons to be clicked. Also we can simply use the default constructor.

EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>();

  1. You’ll notice that we cannot instantiate an EventHandler. So we will create a way of doing so using what is called in-line notation. At the same time, we will also have to implement the inherited abstract method called handle. However, for now we will leave it empty.

//Creating the mouse event handler

EventHandler<MouseEvent> eventHandler = new EventHandler<MouseEvent>()

{

@Override

public void handle(MouseEvent e)

{

}

};

  1. At this point, it should be compliable and so we have completed making an EventHandler object.

Task 4 – Create an Event Listener

            Lastly, we will create an event listener to handle the events (buttons being pushed) and display a message, on the GUI, saying which number button was pushed.

            For Java:

  1. First we will need to create a Text object. Use the overloaded constructor and pass in the string that should be displayed (similar to the button). Also make sure to add it to the GridPane.
  2. Then we attach the EventHandler to a button using the Button class’s addEventFilter method that takes in an event (in this case MouseEvent.MOUSE_CLICKED) and the EventHandler we made earlier.
  3. Finally using the handle method that we left blank earlier, add some code to it so that the method is changing the text to display which button was clicked on. (This may require more than one EventHandler).

           

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

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

//ButtonDemo.java

import javafx.application.Application;

import static javafx.application.Application.launch;

import javafx.event.EventHandler;

import javafx.geometry.Pos;

import javafx.scene.Scene;

import javafx.scene.control.Button;

import javafx.scene.input.MouseEvent;

import javafx.scene.layout.GridPane;

import javafx.scene.text.Text;

import javafx.stage.Stage;

public class ButtonDemo extends Application {

   

    //declaring 5 buttons and a Text object

    Button btn1, btn2, btn3, btn4, btn5;

    Text result;

    @Override

    public void start(Stage primaryStage) {

        //creating a GridPane

        GridPane root = new GridPane();

       

        //creating the event handler

        EventHandler<MouseEvent> handler = new EventHandler<MouseEvent>() {

            @Override

            public void handle(MouseEvent event) {

                //finding which button was clicked

                Button btn = (Button) event.getSource();

                //displaying the text of clicked button in result Text object

                result.setText(btn.getText() + " was pushed.");

            }

        };

       

        //creating button 1

        btn1 = new Button("button 1");

        //adding event handler

        btn1.addEventFilter(MouseEvent.MOUSE_CLICKED, handler);

        //adding to grid pane at column = 0, row = 0

        root.add(btn1, 0, 0);

        //similarly, creating and adding remaining buttons, all in separate columns, but in the same row

        btn2 = new Button("button 2");

        btn2.addEventFilter(MouseEvent.MOUSE_CLICKED, handler);

        root.add(btn2, 1, 0);

        btn3 = new Button("button 3");

        btn3.addEventFilter(MouseEvent.MOUSE_CLICKED, handler);

        root.add(btn3, 2, 0);

        btn4 = new Button("button 4");

        btn4.addEventFilter(MouseEvent.MOUSE_CLICKED, handler);

        root.add(btn4, 3, 0);

        btn5 = new Button("button 5");

        btn5.addEventFilter(MouseEvent.MOUSE_CLICKED, handler);

        root.add(btn5, 4, 0);

       

        //initializing the Text object

        result = new Text();

        //adding to pane at column = 0, row = 1, with column span = 3 (will occupy the space of 3 columns) and

        //row span of 1 (will occupy the space of only 1 row)

        root.add(result, 0, 1, 3, 1);

       

        //aligning pane at center, and setting 20 as space between components vertically

        root.setAlignment(Pos.CENTER);

        root.setVgap(20);

        //setting up and displaying a scene

        Scene scene = new Scene(root, 600, 300);

        primaryStage.setScene(scene);

        primaryStage.show();

    }

    public static void main(String[] args) {

        launch(args);

    }

}

/*OUTPUT*/


Add a comment
Know the answer?
Add Answer to:
JAVA SOLUTION This lab has four parts: Create a window. Create 5 buttons in that window....
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
  • 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)...

  • 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...

  • 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) { //...

  • JAVA problem: Upgrade and extend the previous programs Draw.java and DrawCanvas.java used in the class to...

    JAVA problem: Upgrade and extend the previous programs Draw.java and DrawCanvas.java used in the class to maintain a list of shapes drawn as follows: Replace and upgrade all the AWT components used in the programs to the corresponding Swing components, including Frame, Button, Label, Choice, and Panel. Add a JList to the left of the canvas to record and display the list of shapes that have been drawn on the canvas. Each entry in the list should contain the name...

  • Please Help, JavaFX assignment. This assignment will focus on the use anonymous inner class handlers to...

    Please Help, JavaFX assignment. This assignment will focus on the use anonymous inner class handlers to implement event handling. Assignment 12 Assignment 12 Submission Follow the directions below to submit Assignment 12: This assignment will be a modification of the Assignment 11 program. This program should use the controls and layouts from the previous assignment. No controls or layouts should be added or removed for this assignment. Add event handlers for the three buttons. The event handlers should be implemented...

  • I mainly need help with the “Mouse Events” & “Command Buttons” sections Sqrt xA2 Cir CircleButton...

    I mainly need help with the “Mouse Events” & “Command Buttons” sections Sqrt xA2 Cir CircleButton Clas:s The graphic circular buttons are created by drawing a filled Circle on a StackPane. So, the pictured GUI uses 9 different StackPanes tor displaying the 9 qraphic buttons. Of course, these CircleButton objects can then be placed on a single GridPane lo achieve the 3x3 layoul (see SimpleCalc class below). Creale a class narned CircleBullon thal exlends the StackPane class. The class should...

  • Java Painter Class This is the class that will contain main. Main will create a new...

    Java Painter Class This is the class that will contain main. Main will create a new Painter object - and this is the only thing it will do. Most of the work is done in Painter’s constructor. The Painter class should extend JFrame in its constructor.  Recall that you will want to set its size and the default close operation. You will also want to create an overall holder JPanel to add the various components to. It is this JPanel that...

  • PYTHON Task 1 Create a class called Window It has 2 public properties 1 private property...

    PYTHON Task 1 Create a class called Window It has 2 public properties 1 private property 1 constructor that takes 3 arguments pass each argument to the appropriate property Task 2 In a new file import the Window class Instantiate the Window object Output the two public properties Task 3 Alter the Window class in Task 1 Add an accessor and mutator (the ability to access and change) to the private property Task 4 Create a class named Instrument Give...

  • The JavaFX framework provides more than one way to handle events. For event handlers, we could...

    The JavaFX framework provides more than one way to handle events. For event handlers, we could use inner classes, anonymous inner classes, or the new Java 8 feature of lambda expressions. In this discussion, you will explore these different ways of writing event handles in JavaFX. To prepare for this discussion, you must unzip the attached NetBeans project zip file (U4D1_HandleEvents.zip) and load it into your NetBeans IDE. The project uses an inner class to handle the click event on...

  • Using the template below create a GUI with a push button event. Use a JTextArea to...

    Using the template below create a GUI with a push button event. Use a JTextArea to display which button was selected. /******************* Name: Date: Notes:     *******************/ import javax.swing.*; import java.awt.*; import java.awt.event.*; class Actions extends JFrame implements ActionListener { Create the components (textarea and buttons)    public Actions()    {      create the window (include a close operation)              create the container (include FlowLayout)           add the event listeners (button.addActionListener)           add the components      }           public...

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