Exercise 14.7

This Program is meant to display a 10×10 Grid including a randomly generated ‘0’ or ‘1 within each square.

First, The Imports of all needed JavaFX classes

import java.util.Random;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

Here are the Class declaration and Main method. The class must extend the Application class in order to get the graphical representation we want.

public class Test extends Application {

public static void main(String[] args) {


Next, we want to declare the start of our stage. This method is overridden from the Application class.

public void start(Stage primaryStage) throws Exception {
Random rand = new Random();

Now, we are at the creation of our GridPane. This is what is going to create the “boxes” that the random 1’s and 0’s will fit into. We want to make sure the lines are visible to the user so we force to value of setGridLinesVisible() to true.

GridPane layout = new GridPane();
layout.setPadding(new Insets(10, 10, 10, 10));

Here is where this gets interesting. This for loop steps through each row and column to create a text field in each “box” created by our grid’s lines. You will also notice that each time a text field is created a random number is also generated and displayed in that text field before moving on. This is why we needed the new Random() above.
The if and nested if statements are what give us the exact number of rows and columns needed. The add() method is what actually pushes the newly generated text field and random number to the Grid each time the loop is iterated.

int j = 0;
for (int i = 0; i < 11; i++) {

int newRandomNum = rand.nextInt((1 - 0) + 1) + 0;
TextField number = new TextField();

if (i > 9) {
if (j > 8) {
} else {
i = 0;

layout.add(number, j, i);


Here in the final step, create a new 300px by 300px Scene for our Grid to be displayed upon. The Scene is then set on our Stage and the stage is displayed.

Scene scene = new Scene(layout, 300, 300);




End of code

Exercise 14.7

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s