'Styling and organizing nodes inside a scene

I want to do the following things:

  • Organize my JavaFX code's nodes

  • Increase the size of my combo boxes a little bit

  • Change the scene background's color.

My current code actually looks like this:

   welcome message
                    small combo boxes
 submit               reset
                         result message

The result should be like this:

     Welcome message
      combo boxes
   submit       reset
      result message

Here is my code:

package com.example.team9project;

import javafx.application.Application;
import javafx.css.Size;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;

import java.util.ArrayList;

public class MagicSquare2 extends Application {
    // user-friendly text entries for the matrix
    // using combo boxes to allow user to choose or type their choice
    ComboBox<String> [][] fields = new ComboBox[3][3];

    // labels to display messages to the user
    Label welcome = new Label();
    Label result = new Label();

    GridPane gridPane = new GridPane(); // the appropriate pane for a matrix

    final int correctSum = 15; // helpful variable for isMagicSquare method

    public void start(Stage primaryStage) {
        Background red = new Background(new BackgroundFill(Color.RED, null, null));
        Background blue = new Background(new BackgroundFill(Color.BLUE, null, null));

        // creating buttons
        Button submit = new Button("Submit");
        submit.backgroundProperty().set(red);
        submit.setTextFill(Color.WHITE);

        Button reset = new Button("Reset");
        reset.backgroundProperty().set(blue);
        reset.setTextFill(Color.WHITE);

        // designing the labels
        welcome.setAlignment(Pos.TOP_CENTER);
        welcome.setFont(new Font("Arial",40));
        welcome.setTextFill(Color.RED);

        result.setFont(new Font("Arial",30));
        result.setTextFill(Color.RED);

        welcome.setText(" Welcome to Magic Square Game ");

        // designing the pane
        gridPane.setAlignment(Pos.CENTER);
        gridPane.setPadding(new Insets(11.5,12.5,13.5,14.5));
        gridPane.setHgap(5.5);
        gridPane.setVgap(5.5);

        // adding elements to the pane
        gridPane.add(welcome, 0, 0);
        gridPane.add(submit, 0, 4, 1, 1);
        gridPane.add(reset, 1, 4, 1, 1);
        gridPane.add(result, 1, 5, 1, 1);

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                fields[i][j] = new ComboBox<>();
                fields[i][j].setEditable(true); // enabling user input for combo boxes
                fields[i][j].getItems().addAll("1", "2", "3", "4", "5", "6", "7", "8", "9"); // adding the choices for the combo boxes

                gridPane.add(fields[i][j], i+1, j+1);
            }
        }

        // link reset button with its handler
        reset.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                for (int i = 0; i < 3; i++) {
                    for (int j = 0; j < 3; j++) {
                        fields[i][j].setValue(""); // emptying the entries for the next attempt
                    }
                }

                // remove the previous result from the screen
                result.setText(" Enter the numbers again please");
            }
        });

        // link the submit button with its handler
        SubmitHandler handler1 = new SubmitHandler();
        submit.setOnAction(handler1);

        // adding the grid pane to the scene
        Scene scene = new Scene(gridPane, 550, 160, Color.rgb(153, 196, 200));

        // adding the scene to the stage
        primaryStage.setScene(scene);
     
        // setting the title for the program
        primaryStage.setTitle("Magic Square");

        primaryStage.show();
    }

    // return true if the array represents a square matrix and false otherwise
    public boolean isMagicSquare(int[][] myArray, ArrayList<Integer> arrayList) {
        int sumRow = 0, sumMdg = 0, sumColumn = 0, sumSdg = 0; // creating useful variables

        // using ArrayList check if elements are duplicated or out of the interval
        for (int i = 0; i < arrayList.size(); i++) {
            if (arrayList.get(i) > 9 || arrayList.get(i) < 0)
                return false;

            // check if numbers are repeated
            int element = arrayList.get(i);
            arrayList.remove(i);
            if (arrayList.contains(element))
                return false;
        }

        // check the sum of columns, rows, diagnols
        for(int i = 0; i < myArray.length; i++) {
            sumRow = sumColumn = 0;
            sumMdg += myArray[i][i];
            sumSdg += myArray[i][myArray.length - 1 - i];

            for (int j = 0; j < myArray.length; j++) {
                sumRow += myArray[i][j];
                sumColumn += myArray[j][i];
            }

            if (sumColumn != correctSum || sumRow != correctSum)
                return false;
        }

        return (sumMdg == correctSum) && (sumSdg == correctSum);
    }

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

    class SubmitHandler implements EventHandler<ActionEvent> {
        @Override
        public void handle(ActionEvent event) {
            // Array full of the usre's choices that will be passed to isMagicSquare method.
            int[][] values = new int[3][3];
            // Array list to  easily check if numbers are duplicated or >9 or<0
            ArrayList<Integer> arrayList = new ArrayList<>(9);
            // try statement to handle user's invalid inputs such as words("one","two",....)
            try {
                for (int i = 0; i < 3; i++) {
                    for (int j = 0; j < 3; j++) {
                        // check if the fields are empty
                        if (fields[i][j].getValue().compareTo("") == 0) {
                            fields[i][j].setValue("0");
                        }

                        values[i][j] = Integer.parseInt(fields[i][j].getValue()); // convert the user choices to integers
                        arrayList.add(values[i][j]); // add elemnts to the one-dimensional array
                    }
                }
            } catch (Exception NumberFormatException) {
                result.setText(" You entered an invalid input. Please try again");
                return;
            }

            if (isMagicSquare(values, arrayList)) {
                result.setText("The matrix is a magic square  ");
            } else {
                result.setText("The matrix is not a magic square. Try again please");
            }
        }
    }
}


Solution 1:[1]

use columnSpam to spam a node horizontally

columnspam

now label result and wellcome uses 4 columns size. check columnSpam() at gridpane(javafx8)

to change scene color : scene.setFill()

I added comments where code was modified

public class MagicSquare2 extends Application {
    // user-friendly text entries for the matrix
    // using combo boxes to allow user to choose or type their choice
    ComboBox<String> [][] fields = new ComboBox[3][3];

    // labels to display messages to the user
    Label welcome = new Label();
    Label result = new Label();

    GridPane gridPane = new GridPane(); // the appropriate pane for a matrix

    final int correctSum = 15; // helpful variable for isMagicSquare method

    public void start(Stage primaryStage) {
        Background red = new Background(new BackgroundFill(Color.RED, null, null));
        Background blue = new Background(new BackgroundFill(Color.BLUE, null, null));

        // creating buttons
        Button submit = new Button("Submit");
        submit.backgroundProperty().set(red);
        submit.setTextFill(Color.WHITE);

        Button reset = new Button("Reset");
        reset.backgroundProperty().set(blue);
        reset.setTextFill(Color.WHITE);

        // designing the labels
        welcome.setAlignment(Pos.TOP_CENTER);
        welcome.setFont(new Font("Arial",40));
        welcome.setTextFill(Color.RED);

        result.setFont(new Font("Arial",30));
        result.setTextFill(Color.RED);

        welcome.setText(" Welcome to Magic Square Game ");

        // designing the pane
        gridPane.setAlignment(Pos.CENTER);
        gridPane.setPadding(new Insets(11.5,12.5,13.5,14.5));
        gridPane.setHgap(5.5);
        gridPane.setVgap(5.5);
//        gridPane.setGridLinesVisible(true);

        // adding elements to the pane
        gridPane.setColumnSpan(welcome, 4); //columnspam
        gridPane.add(welcome, 0, 0);
        gridPane.add(submit, 1, 4, 1, 1);
        gridPane.add(reset, 3, 4, 1, 1);
        gridPane.setColumnSpan(result, 4);//columspam
        gridPane.add(result, 0, 5);

        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                fields[i][j] = new ComboBox<>();
                fields[i][j].setEditable(true); // enabling user input for combo boxes
                fields[i][j].getItems().addAll("1", "2", "3", "4", "5", "6", "7", "8", "9"); // adding the choices for the combo boxes

                gridPane.add(fields[i][j], i+1, j+1);
            }
        }

        // link reset button with its handler
        reset.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                for (int i = 0; i < 3; i++) {
                    for (int j = 0; j < 3; j++) {
                        fields[i][j].setValue(""); // emptying the entries for the next attempt
                    }
                }

                // remove the previous result from the screen
                result.setText(" Enter the numbers again please");
            }
        });

        // link the submit button with its handler
        SubmitHandler handler1 = new SubmitHandler();
        submit.setOnAction(handler1);

        // adding the grid pane to the scene
        Scene scene = new Scene(gridPane, 550, 160, Color.rgb(153, 196, 200));
         scene.setFill(Color.CYAN); // change color scene
        // adding the scene to the stage
        primaryStage.setScene(scene);
     
        // setting the title for the program
        primaryStage.setTitle("Magic Square");

        primaryStage.show();
    }

    // return true if the array represents a square matrix and false otherwise
    public boolean isMagicSquare(int[][] myArray, ArrayList<Integer> arrayList) {
        int sumRow = 0, sumMdg = 0, sumColumn = 0, sumSdg = 0; // creating useful variables

        // using ArrayList check if elements are duplicated or out of the interval
        for (int i = 0; i < arrayList.size(); i++) {
            if (arrayList.get(i) > 9 || arrayList.get(i) < 0)
                return false;

            // check if numbers are repeated
            int element = arrayList.get(i);
            arrayList.remove(i);
            if (arrayList.contains(element))
                return false;
        }

        // check the sum of columns, rows, diagnols
        for(int i = 0; i < myArray.length; i++) {
            sumRow = sumColumn = 0;
            sumMdg += myArray[i][i];
            sumSdg += myArray[i][myArray.length - 1 - i];

            for (int j = 0; j < myArray.length; j++) {
                sumRow += myArray[i][j];
                sumColumn += myArray[j][i];
            }

            if (sumColumn != correctSum || sumRow != correctSum)
                return false;
        }

        return (sumMdg == correctSum) && (sumSdg == correctSum);
    }

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

    class SubmitHandler implements EventHandler<ActionEvent> {
        @Override
        public void handle(ActionEvent event) {
            // Array full of the usre's choices that will be passed to isMagicSquare method.
            int[][] values = new int[3][3];
            // Array list to  easily check if numbers are duplicated or >9 or<0
            ArrayList<Integer> arrayList = new ArrayList<>(9);
            // try statement to handle user's invalid inputs such as words("one","two",....)
            try {
                for (int i = 0; i < 3; i++) {
                    for (int j = 0; j < 3; j++) {
                        // check if the fields are empty
                        if (fields[i][j].getValue().compareTo("") == 0) {
                            fields[i][j].setValue("0");
                        }

                        values[i][j] = Integer.parseInt(fields[i][j].getValue()); // convert the user choices to integers
                        arrayList.add(values[i][j]); // add elemnts to the one-dimensional array
                    }
                }
            } catch (Exception NumberFormatException) {
                result.setText(" You entered an invalid input. Please try again");
                return;
            }

            if (isMagicSquare(values, arrayList)) {
                result.setText("The matrix is a magic square  ");
            } else {
                result.setText("The matrix is not a magic square. Try again please");
            }
        }
    }
} 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Giovanni Contreras