Question: JavaFX Create a JavaFX application that rolls two dice using the Random Class and Imageview. When two random numbers are generated show the correct image

JavaFX

Create a JavaFX application that rolls two dice using the Random Class and Imageview. When two random numbers are generated show the correct image of the number generated for each dice. Supply the sum of the two rolls in a label. Each time you click a button both dice are "rolled" again. PLEASE ADD ADDITIONAL CODING TO CODE BELOW.

Current Code:

import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.FlowPane; import javafx.stage.Stage;

public class Dice extends Application {

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

@Override public void start(Stage stage){

// Creating two ImageViews for two dice

ImageView dice1 = new ImageView(); dice1.setFitHeight(200); dice1.setFitWidth(150);

ImageView dice2 = new ImageView(); dice2.setFitHeight(200); dice2.setFitWidth(150);

// Creating a button to generate random die

Button toss = new Button("Roll Dice");

toss.setOnAction(new EventHandler() { @Override public void handle(ActionEvent event) {

dice1.setImage(new Image(getRandomDice())); dice2.setImage(new Image(getRandomDice())); } });

FlowPane pane = new FlowPane(); pane.getChildren().addAll(dice1, dice2, toss); // Adding imageviews and button as well

Scene scene = new Scene(pane, 320, 250); stage.setScene(scene); stage.setTitle("Rolling A Pair Of Dice"); stage.show(); }

public static String getRandomDice() {

int number = (int) (Math.random()*(6 -1 + 1)) + 1;

String pic = "";

if(number == 1) pic = "Die1.bmp"; else if(number == 2) pic = "Die2.bmp"; else if(number == 3) pic = "Die3.bmp"; else if(number == 4) pic = "Die4.bmp"; else if(number == 5) pic = "Die5.bmp"; else if(number == 6) pic = "Die6.bmp";

return pic; } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!