I want to write code, that can do following:
-
Create 9*9 GridPane board that filled with 81 StackPanes.
-
When I click on cell (StackPane) I want to change color of background StackPane to blue if it is white. If I have alreday had blue cell on board, than old cell becomes white and new one becomes blue. So, In anytime I can only have 0 or 1 colored cell.
-
I tried to use Array[9][9] of StackPanes but I failed because even if I declare this array before “public void start(Stage stage)” I fail to use each StackPane in lambda expressions or innerclasses.
-
I tried to use variable that tells if I have 1 colored cell or not and coordinates of colored cell in 2 variables. When I click on cells I see that coordinates works, but I can’t change color of Panes.
package com.example.testingcolorswitching;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.scene.shape.Line;
import javafx.stage.Stage;
import java.io.IOException;
public class HelloApplication extends Application {
boolean isAnyPaneSelected = true; // true if 1 of cells is selected
int xColored = 1; // holds X coordinate of Selected cell;
int yColored = 1; // holds Y coordinate of Selected cell;
int columnSize = 50;
int rowSize = 50;
@Override
public void start(Stage stage) throws IOException {
GridPane grid = new GridPane();
for (int x = 0; x < 9; x++)
for (int y = 0; y < 9; y++){
StackPane cell = new StackPane();
cell.setMinSize(columnSize, rowSize);
// I would like that this was checked every time I click on GridPane
if (isAnyPaneSelected && x == xColored && y == yColored)
cell.setStyle("-fx-background-color:BLUE");
final int thisX = x;
final int thisY = y;
cell.setOnMouseClicked((event) -> {
if(isAnyPaneSelected) {
if (thisX == xColored & thisY == yColored)
isAnyPaneSelected = false;
else {
xColored = thisX;
yColored = thisY;
}
} else {
isAnyPaneSelected = true;
xColored = thisX;
yColored = thisY;
}
System.out.println(isAnyPaneSelected + " " + xColored + " " + yColored);
});
grid.add(cell, x, y);
}
// code below is not important. This code adds lines on screen.
for (int i = 0; i <= 9; i++){
Line line = new Line(0.0, rowSize * i, rowSize * 9, rowSize * i);
line.setManaged(false);
if (i % 3 == 0)
line.setStrokeWidth(3);
else
line.setStrokeWidth(1);
grid.getChildren().add(line);
line = new Line(columnSize * i, 0.0, columnSize * i, columnSize * 9);
line.setManaged(false);
if (i % 3 == 0)
line.setStrokeWidth(3);
else
line.setStrokeWidth(1);
grid.getChildren().add(line);
}
Scene scene = new Scene(grid, 600, 600);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch();
}
}
Andrey L is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.