Sunday, October 26, 2014

JavaFX Nr.4

(Game: display a checkerboard) Write a program that displays a checkerboard
in which each white and black cell is a  Rectangle with a fill color black or
white, as shown in figure.

Solution:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class Checkboard extends Application {

@Override
public void start(Stage primaryStage) {
Pane pane = new Pane();
int i = 0;
int j = 0;

for(i = 0; i < 8; i++) {
for(j = 0; j < 8; j++) {
Rectangle rec = new Rectangle(20 * j, 20 * i, 20, 20);
if(i + j % 2 == 1) {
rec.setFill(Color.BLACK);
} else {
rec.setFill(Color.WHITE);
}

pane.getChildren().add(rec);
}
}

Scene scene = new Scene(pane, 160, 160);
primaryStage.setTitle("Checkboard");
primaryStage.setScene(scene);
primaryStage.show();
}

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

5 comments:

  1. When I tried out your example it looks to me that there is something wrong with the modulo operation as the first two rows get their squares' color correctly, though all the squares for beginning with row three get a white color. Didn't do any further examination, quick and dirty did a color toggle in case the column is not the first one and we have an even number of columns (used y for i and x for j):

    if ( (width % 2 == 0 && x != 0 ) || width % 2 != 0 ) { ... do a color toggle ... }

    Maybe it helps :-)

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. If you add parentheses around the i+j in the if statement it works

    ReplyDelete
  4. If you add parentheses around the i+j in the if statement it works

    ReplyDelete
  5. Great and I have a super proposal: Where To Buy Houses For Renovation small house renovation

    ReplyDelete

Author