I would like to display a grid containing a various number of rectangles in JavaFX. It is important that this grid cannot be resized.
I chose the GridPane layout. I dynamically add javafx.scene.shape.Rectangle to it. Here's how my grid looks like with 2 rows and 4 columns.
Upon resizing, I would like it to keep the same overall shape, that is to say each Rectangle having the same size and keeping an horizontal and vertical gaps between my Rectangles.
However, here's what I get with a 4x4 grid:
The problems being:
The last row and last column do not have the same size as the rest of the Rectangles.
The gaps have disappeared.
Here is my code responsible for refreshing the display:
public void refreshConstraints() {
getRowConstraints().clear();
getColumnConstraints().clear();
for (int i = 0; i < nbRow; i++) {
RowConstraints rConstraint = new RowConstraints();
// ((nbRow - 1) * 10 / nbRow) = takes gap into account (10% of height)
rConstraint.setPercentHeight(100 / nbRow - ((nbRow - 1) * 10 / nbRow));
getRowConstraints().add(rConstraint);
}
for (int i = 0; i < nbColumn; i++) {
ColumnConstraints cConstraint = new ColumnConstraints();
cConstraint.setPercentWidth(100 / nbColumn - ((nbColumn - 1) * 10 / nbColumn));
getColumnConstraints().add(cConstraint);
}
}
Using the setFillWidth and setHgrow yields no result either, the gap is kept between my Rectangles, but the Rectangles aren't resized and they overlap the rest of my GUI elements.
EDIT: MCVE code:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.RowConstraints;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class DynamicGrid extends Application {
//Class containing grid (see below)
private GridDisplay gridDisplay;
#Override
public void start(Stage primaryStage) {
//Represents the grid with Rectangles
gridDisplay = new GridDisplay(400, 200);
//Fields to specify number of rows/columns
TextField rowField = new TextField();
TextField columnField = new TextField();
//Function to set an action when text field loses focus
buildTextFieldActions(rowField, columnField);
HBox fields = new HBox();
fields.getChildren().add(rowField);
fields.getChildren().add(new Label("x"));
fields.getChildren().add(columnField);
BorderPane mainPanel = new BorderPane();
mainPanel.setLeft(gridDisplay.getDisplay());
mainPanel.setBottom(fields);
Scene scene = new Scene(mainPanel);
primaryStage.setTitle("Test grid display");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
private void buildTextFieldActions(final TextField rowField, final TextField columnField) {
rowField.focusedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
if (!t1) {
if (!rowField.getText().equals("")) {
try {
int nbRow = Integer.parseInt(rowField.getText());
gridDisplay.setRows(nbRow);
gridDisplay.updateDisplay();
} catch (NumberFormatException nfe) {
System.out.println("Please enter a valid number.");
}
}
}
}
});
columnField.focusedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) {
if (!t1) {
if (!columnField.getText().equals("")) {
try {
int nbColumn = Integer.parseInt(columnField.getText());
gridDisplay.setColumns(nbColumn);
gridDisplay.updateDisplay();
} catch (NumberFormatException nfe) {
System.out.println("Please enter a valid number.");
}
}
}
}
});
}
//Class responsible for displaying the grid containing the Rectangles
public class GridDisplay {
private GridPane gridPane;
private int nbRow;
private int nbColumn;
private int width;
private int height;
private double hGap;
private double vGap;
public GridDisplay(int width, int height) {
this.gridPane = new GridPane();
this.width = width;
this.height = height;
build();
}
private void build() {
this.hGap = 0.1 * width;
this.vGap = 0.1 * height;
gridPane.setVgap(vGap);
gridPane.setHgap(hGap);
gridPane.setPrefSize(width, height);
initializeDisplay(width, height);
}
//Builds the first display (correctly) : adds a Rectangle for the number
//of rows and columns
private void initializeDisplay(int width, int height) {
nbRow = height / 100;
nbColumn = width / 100;
for (int i = 0; i < nbColumn; i++) {
for (int j = 0; j < nbRow; j++) {
Rectangle rectangle = new Rectangle(100, 100);
rectangle.setStroke(Paint.valueOf("orange"));
rectangle.setFill(Paint.valueOf("steelblue"));
gridPane.add(rectangle, i, j);
}
}
}
//Function detailed in post
//Called in updateDisplay()
public void refreshConstraints() {
gridPane.getRowConstraints().clear();
gridPane.getColumnConstraints().clear();
for (int i = 0; i < nbRow; i++) {
RowConstraints rConstraint = new RowConstraints();
rConstraint.setPercentHeight(100 / nbRow - ((nbRow - 1) * 10 / nbRow));
gridPane.getRowConstraints().add(rConstraint);
}
for (int i = 0; i < nbColumn; i++) {
ColumnConstraints cConstraint = new ColumnConstraints();
cConstraint.setPercentWidth(100 / nbColumn - ((nbColumn - 1) * 10 / nbColumn));
gridPane.getColumnConstraints().add(cConstraint);
}
}
public void setColumns(int newColumns) {
nbColumn = newColumns;
}
public void setRows(int newRows) {
nbRow = newRows;
}
public GridPane getDisplay() {
return gridPane;
}
//Function called when refreshing the display
public void updateDisplay() {
Platform.runLater(new Runnable() {
#Override
public void run() {
//The gridpane is cleared of the previous children
gridPane.getChildren().clear();
//A new rectangle is added for row*column
for (int i = 0; i < nbColumn; i++) {
for (int j = 0; j < nbRow; j++) {
Rectangle rectangle = new Rectangle(100, 100);
rectangle.setStroke(Paint.valueOf("orange"));
rectangle.setFill(Paint.valueOf("steelblue"));
gridPane.add(rectangle, i, j);
}
}
//Call to this function to update the grid's constraints
refreshConstraints();
}
});
}
}
}
Seems like a TilePane is a better fit for this use case than a GridPane.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.TilePane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
// java 8 code
public class DynamicTiles extends Application {
//Class containing grid (see below)
private GridDisplay gridDisplay;
//Class responsible for displaying the grid containing the Rectangles
public class GridDisplay {
private static final double ELEMENT_SIZE = 100;
private static final double GAP = ELEMENT_SIZE / 10;
private TilePane tilePane = new TilePane();
private Group display = new Group(tilePane);
private int nRows;
private int nCols;
public GridDisplay(int nRows, int nCols) {
tilePane.setStyle("-fx-background-color: rgba(255, 215, 0, 0.1);");
tilePane.setHgap(GAP);
tilePane.setVgap(GAP);
setColumns(nCols);
setRows(nRows);
}
public void setColumns(int newColumns) {
nCols = newColumns;
tilePane.setPrefColumns(nCols);
createElements();
}
public void setRows(int newRows) {
nRows = newRows;
tilePane.setPrefRows(nRows);
createElements();
}
public Group getDisplay() {
return display;
}
private void createElements() {
tilePane.getChildren().clear();
for (int i = 0; i < nCols; i++) {
for (int j = 0; j < nRows; j++) {
tilePane.getChildren().add(createElement());
}
}
}
private Rectangle createElement() {
Rectangle rectangle = new Rectangle(ELEMENT_SIZE, ELEMENT_SIZE);
rectangle.setStroke(Color.ORANGE);
rectangle.setFill(Color.STEELBLUE);
return rectangle;
}
}
#Override
public void start(Stage primaryStage) {
//Represents the grid with Rectangles
gridDisplay = new GridDisplay(2, 4);
//Fields to specify number of rows/columns
TextField rowField = new TextField("2");
TextField columnField = new TextField("4");
//Function to set an action when text field loses focus
buildTextFieldActions(rowField, columnField);
HBox fields = new HBox(10);
fields.getChildren().add(rowField);
fields.getChildren().add(new Label("x"));
fields.getChildren().add(columnField);
BorderPane mainPanel = new BorderPane();
mainPanel.setCenter(gridDisplay.getDisplay());
mainPanel.setTop(fields);
Scene scene = new Scene(mainPanel, 1000, 800);
primaryStage.setTitle("Test grid display");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
private void buildTextFieldActions(final TextField rowField, final TextField columnField) {
rowField.focusedProperty().addListener((ov, t, t1) -> {
if (!t1) {
if (!rowField.getText().equals("")) {
try {
int nbRow = Integer.parseInt(rowField.getText());
gridDisplay.setRows(nbRow);
} catch (NumberFormatException nfe) {
System.out.println("Please enter a valid number.");
}
}
}
});
columnField.focusedProperty().addListener((ov, t, t1) -> {
if (!t1) {
if (!columnField.getText().equals("")) {
try {
int nbColumn = Integer.parseInt(columnField.getText());
gridDisplay.setColumns(nbColumn);
} catch (NumberFormatException nfe) {
System.out.println("Please enter a valid number.");
}
}
}
});
}
}
Thanks a lot for your answer. TilePanes are indeed a lot easier to use, although what you've written does not completely answer my question.
I wanted to have a pane in which the children would resize, and not the pane itself. It seems setting the maxSize and prefSize doesn't have any effect.
EDIT: I managed to do it using two JavaFX Property in my GridDisplay class, corresponding to the fixed height and width of my grid:
public class GridDisplay {
private ReadOnlyDoubleProperty heightProperty;
private ReadOnlyDoubleProperty widthProperty;
...
}
Then I assign to these members the values corresponding to the desired fixed size in the constructor. The size of the children inside the grid correspond to a fraction of the height and width of the grid, depending on the number of rows and columns. Here's what my updateDisplay() looks like:
public void updateDisplay() {
gridPane.getChildren().clear();
for (int i = 0; i < nbColumn; i++) {
for (int j = 0; j < nbRow; j++) {
Rectangle rectangle = new Rectangle(100, 100);
//Binding the fraction of the grid size to the width
//and heightProperty of the child
rectangle.widthProperty().bind(widthProperty.divide(nbColumn));
rectangle.heightProperty().bind(heightProperty.divide(nbRow));
gridPane.add(rectangle, i, j);
}
}
}
Related
I'm developing a chess game using Java and JAVAFX.
My board is a JAVAFX group that contains an array of squares. My squares inherit from the JAVAFX rectangle class. I want to draw an image inside of these squares (image of the pieces) but I can't seem to find a way. when I use setfill to image Pattern the color of the square disappears which is not what I want I want the image to be transparent and drawn on top of each square. Any Ideas?
To place an image on top of a shape you can encapsulate both in a StackPane:
import javafx.application.Application;
import javafx.geometry.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.image.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class Chess extends Application {
private final String[] COLORS = {"black","white"};
private static int ROWS = 4, COLS = 4;
#Override
public void start(Stage stage) {
Board board = new Board(COLS);
int tileNum = 0;
for(int row = 0; row < ROWS ; row++){
tileNum = tileNum == 0 ? 1:0;
for(int col = 0; col < COLS; col++){
Tile tile = new Tile(COLORS[tileNum]);
if(row==ROWS/2 && col == COLS/2) {//place an arbitrary piece
tile.setPiece(Pieces.KING.getImage());
}
board.addTile(tile.getTile());
tileNum = tileNum == 0 ? 1:0;
}
}
Parent root = new Group(board.getBoard());
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
class Board {
private final TilePane board;
public Board(int columns) {
board = new TilePane(Orientation.HORIZONTAL);
board.setPrefColumns(columns);
board.setTileAlignment(Pos.CENTER);
board.setStyle("-fx-border-color:red;");
}
Pane getBoard(){
return board;
}
void addTile(Node node){
board.getChildren().add(node);
}
}
class Tile {
public static final int SIZE = 100;
private final StackPane tile;
Tile(String colorName) {
this(colorName, null);
}
Tile(String colorName, Image piece) {
Rectangle rect = new Rectangle(SIZE, SIZE, Color.valueOf(colorName));
tile = new StackPane(rect);
tile.setStyle("-fx-border-color:red;");
if(piece != null) {
setPiece(piece);
}
}
void setPiece(Image piece){
tile.getChildren().add(new ImageView(piece));
}
public Node getTile() {
return tile;
}
}
enum Pieces {
KING ("https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/64x64/Circle_Blue.png"),
QUEEN ("https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/64x64/Circle_Orange.png");
private String image;
private Pieces(String image) {
this.image = image;
}
public Image getImage(){
return new Image(image);
}
}
It is quiet simple to change the representation of a tile to a JavaFx control such as Label or Button. All you need to do is some minor changes to Tile:
class Tile {
public static final int SIZE = 100;
private final Label tile;//a Button if you need it clickable
Tile(String colorName) {
this(colorName, null);
}
Tile(String colorName, Image piece) {
tile = new Label();
tile.setPrefSize(SIZE, SIZE);
tile.setStyle("-fx-border-color:red; -fx-background-color:"+colorName);
tile.setAlignment(Pos.CENTER);
if(piece != null) {
setPiece(piece);
}
}
void setPiece(Image piece){
tile.setGraphic(new ImageView(piece));
}
public Node getTile() {
return tile;
}
}
I created an application which generates a board with a grid pattern, consisting of nodes which hold square objects in javaFX, using GridPanel. Below is the current output:
I want to know how to return the coordinate of a node, after CLICKING on the node. I am aware I have to use an action listener of sorts, but I'm not entirely familiar when it comes to having node coordinates.
Below is the current source code, thank you very much.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class MainApp extends Application {
private final double windowWidth = 1000;
private final double windowHeight = 1000;
/*n is amount of cells per row
m is amount of cells per column*/
private final int n = 50;
private final int m = 50;
double gridWidth = windowWidth / n;
double gridHeight = windowHeight / m;
MyNode[][] playfield = new MyNode[n][m];
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Group root = new Group();
// initialize playfield
for( int i=0; i < n; i++) {
for( int j=0; j < m; j++) {
// create node
MyNode node = new MyNode( i * gridWidth, j * gridHeight, gridWidth, gridHeight);
// add node to group
root.getChildren().add( node);
// add to playfield for further reference using an array
playfield[i][j] = node;
}
}
Scene scene = new Scene( root, windowWidth, windowHeight);
primaryStage.setScene( scene);
primaryStage.show();
primaryStage.setResizable(false);
primaryStage.sizeToScene();
}
public static class MyNode extends StackPane {
public MyNode(double x, double y, double width, double height) {
// create rectangle
Rectangle rectangle = new Rectangle( width, height);
rectangle.setStroke(Color.BLACK);
rectangle.setFill(Color.LIGHTGREEN);
// set position
setTranslateX(x);
setTranslateY(y);
getChildren().addAll(rectangle);
}
}
}
You can add mouse event handler to root :
root.setOnMousePressed(e->mousePressedOnRoot(e));
Where mousePressedOnRoot(e) is defined as
private void mousePressedOnRoot(MouseEvent e) {
System.out.println("mouse pressed on (x-y): "+e.getSceneX()+"-"+e.getSceneY());
}
Edit: alternatively you can add mouse event handler to each MyNode instance by adding setOnMousePressed(e->mousePressedOnNode(e)); to its constructor.
and add the method:
private void mousePressedOnNode(MouseEvent e) {
System.out.println("mouse pressed on (x-y): "+e.getSceneX()+"-"+e.getSceneY());
}
If you need the coordinates within the clicked node use e.getX() and e.getY()
Long story short, I have 8x8 GridPane (using it as Chess Board) and I want to be able to click on each cell and get its coordinates.
public class BoardView {
private ImageView imageView = new ImageView(new Image("board.png"));
private GridPane boardGrid = new GridPane();
public void createBoard(){
boardGrid.getChildren().add(imageView);
for(int i =0;i < 8; i++){
for(int j = 0; j < 8; j++){
Tile tile = new Tile(i, j);
GridPane.setConstraints(tile.getPane(), i, j);
boardGrid.getChildren().add(tile.getPane());
}
}
}
class Tile {
private int positionX;
private int positionY;
private Pane pane;
Tile(int x, int y) {
pane = new Pane();
positionX = x;
positionY = y;
pane.setOnMouseClicked(e -> {
System.out.println(positionX + " " + positionY);
}
);
}
}
However, everywhere I click, the result is "0 0", not the actual row/column position.
You code is incomplete some of your errors are :
You haven't give a specific size (width, height) on each Pane (Tiles)
I am guessing you set the size of the GridPane somewhere but its just a guess, now the way you add the background image on your Grid is something that I don't recommend instead use a StackPane.
Here is a small example which you can check to debug your problem.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class BoardView extends Application {
// the dimensions of our background Image
private final int BORDER_WIDTH = 695;
private final int BORDER_HEIGHT = 720;
#Override
public void start(Stage stage) throws Exception {
// Load your Image
ImageView backgroundImageView = new ImageView(
new Image("https://cdn.pixabay.com/photo/2013/07/13/10/24/board-157165_960_720.png"));
// Initialize the grid
GridPane boardGrid = initBoard();
// Set the dimensions of the grid
boardGrid.setPrefSize(BORDER_WIDTH, BORDER_HEIGHT);
// Use a StackPane to display the Image and the Grid
StackPane mainPane = new StackPane();
mainPane.getChildren().addAll(backgroundImageView, boardGrid);
stage.setScene(new Scene(mainPane));
stage.setResizable(false);
stage.show();
}
private GridPane initBoard() {
GridPane boardGrid = new GridPane();
int tileNum = 8;
double tileWidth = BORDER_WIDTH / tileNum;
double tileHeight = BORDER_HEIGHT / tileNum;
for (int i = 0; i < tileNum; i++) {
for (int j = 0; j < tileNum; j++) {
Tile tile = new Tile(i, j);
// Set each 'Tile' the width and height
tile.setPrefSize(tileWidth, tileHeight);
// Add node on j column and i row
boardGrid.add(tile, j, i);
}
}
// Return the GridPane
return boardGrid;
}
class Tile extends Pane {
private int positionX;
private int positionY;
public Tile(int x, int y) {
positionX = x;
positionY = y;
setOnMouseClicked(e -> {
System.out.println(positionX + " " + positionY);
});
}
}
public static void main(String[] args) {
launch(args);
}
}
From my point of view you its more easy to handle each Tile if you made the class to extend the Pane instead of just holding a reference to it but this is just my opinion. Well the above its just an example anyway. If you cant find the problem then post a MCVE show we can help you better.
for this application, I need to enter a number and display the numbers that when multiplied together will give you the number in question. For example, if you enter 42 then the labels for 6*7 and 7*6 would change color. I figured out how to get the answers but I cant quite figure out how to manipulate the labels in the multiplication table to change color. To give you an idea,
main class
package application;
import java.util.List;
import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
BorderPane pane = new BorderPane();
pane.setTop(getHbox1());
HBox prompt = new HBox(15);
prompt.setPadding(new Insets(15, 15, 15, 15));
prompt.setAlignment(Pos.TOP_CENTER);
prompt.getStyleClass().add("hbox2");
Label lblProblem = new Label("Enter problem: ");
prompt.getChildren().add(lblProblem);
TextField tfProblem = new TextField();
prompt.getChildren().add(tfProblem);
Button btnFindAnswer = new Button("Find answers");
btnFindAnswer.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<Event>() {
#Override
public void handle(Event arg0) {
int x = showFactors(tfProblem);
}
});
prompt.getChildren().add(btnFindAnswer);
pane.setCenter(prompt);
pane.setBottom(setUpGrid());
Scene scene = new Scene(pane, 550, 650);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setTitle("lab 7");
primaryStage.setScene(scene);
primaryStage.show();
}
private HBox getHbox1() {
HBox hbox = new HBox(15);
hbox.setPadding(new Insets(15, 15, 15, 15));
hbox.setAlignment(Pos.TOP_CENTER);
hbox.getStyleClass().add("hbox1");
Label lblProblem = new Label("Reverse Multiplication Table");
hbox.getChildren().add(lblProblem);
return hbox;
}
public GridPane setUpGrid() {
GridPane pane = new GridPane();
Label[][] labels = new Label[11][11];
for (int row = 0; row < 11; row++)
for (int col = 0; col < 11; col++) {
Label l = new Label();
setUpLabel(l, col, row);
labels[row][col] = l;
pane.add(l, col, row);
}
return pane;
}
public void setUpLabel(final Label l, final int col, final int row) {
l.setPrefHeight(50);
l.setPrefWidth(50);
l.setAlignment(Pos.CENTER);
l.setStyle("-fx-stroke-border: black; -fx-border-width: 1;");
String a = String.valueOf(row);
String b = String.valueOf(col);
if (row == 0 || col == 0) {
l.getStyleClass().add("gridBorders");
if(row == 0)
l.setText(b);
else if (col == 0)
l.setText(a);
} else {
l.setText(a + " * " + b);
l.getStyleClass().add("gridInside");
}
}
public int showFactors(TextField problem) {
FactorCalculator calc = new FactorCalculator();
int number = Integer.parseInt(problem.getText());
List<Integer> factors = calc.findFactor(number);
for(int i = 0; i < factors.size() - 1; i++) {
return factors.get(i);
}
return 0;
}
public static void main(String[] args) {
launch(args);
}
}
factorCalculator class
package application;
import java.util.ArrayList;
import java.util.List;
public class FactorCalculator {
public List<Integer> list = new ArrayList<Integer>();
public List<Integer> findFactor(int problem) {
int incrementer = 1;
if(problem % 2 != 0) {
incrementer = 2;
}
while(incrementer <= problem) {
if(problem % incrementer == 0) {
list.add(incrementer);
}
incrementer++;
}
return list;
}
}
application css
{
-fx-text-alignment: center;
}
.hbox1 {
-fx-background-color: gray;
}
.hbox2 {
-fx-background-color: white;
}
.gridBorders {
-fx-background-color: gray;
-fx-text-fill:#A3FF47;
-fx-border-style: solid;
-fx-border-width: 1;
-fx-stroke-border: black;
}
.gridInside {
-fx-background-color: red;
-fx-text-fill: white;
-fx-border-style: solid;
-fx-border-width: 1;
-fx-stroke-border: black;
}
.gridAnswer {
-fx-background-color: white;
-fx-text-fill: black;
}
Just use your style "gridAnswer" and set it
l.getStyleClass().add( "gridAnswer");
or remove it
l.getStyleClass().remove( "gridAnswer");
depending on your needs.
Edit: May I suggest a different approach?
Just create a custom cell which has all the information you need. Something like this:
private class AnswerCell extends Label {
int a;
int b;
int value;
public AnswerCell( int a, int b) {
this.a = a;
this.b = b;
this.value = a * b;
setText( a + " * " + b);
}
public boolean matches( int matchValue) {
return value == matchValue;
}
public void highlight() {
getStyleClass().add( "gridAnswer");
}
public void unhighlight() {
getStyleClass().remove( "gridAnswer");
}
}
In your setup method you simply add the cells and put them into a global list:
List<AnswerCell> answerCells = new ArrayList<>();
And to find the answers you do this:
for( AnswerCell cell: answerCells) {
cell.unhighlight();
}
for( AnswerCell cell: answerCells) {
if( cell.matches(number)) {
cell.highlight();
}
}
ReverseMultiplication.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package reversemultiplication;
import java.util.List;
import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
/**
*
* #author reegan
*/
public class ReverseMultiplication extends Application {
#Override
public void start(Stage primaryStage) {
BorderPane pane = new BorderPane();
pane.setTop(getHbox1());
HBox prompt = new HBox(15);
prompt.setPadding(new Insets(15, 15, 15, 15));
prompt.setAlignment(Pos.TOP_CENTER);
prompt.getStyleClass().add("hbox2");
Label lblProblem = new Label("Enter problem: ");
prompt.getChildren().add(lblProblem);
TextField tfProblem = new TextField();
prompt.getChildren().add(tfProblem);
GridPane gridPane = setUpGrid();
GridpaneHelper gh = new GridpaneHelper(gridPane);
Button btnFindAnswer = new Button("Find answers");
btnFindAnswer.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<Event>() {
#Override
public void handle(Event arg0) {
List<int[]> x = showFactors(tfProblem);
for (int[] x1 : x) {
Node node = gh.getChildren()[x1[0]][x1[1]];
node.setStyle("-fx-background-color: green");
}
}
});
prompt.getChildren().add(btnFindAnswer);
pane.setCenter(prompt);
pane.setBottom(gridPane);
Scene scene = new Scene(pane, 550, 650);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setTitle("lab 7");
primaryStage.setScene(scene);
primaryStage.show();
}
private HBox getHbox1() {
HBox hbox = new HBox(15);
hbox.setPadding(new Insets(15, 15, 15, 15));
hbox.setAlignment(Pos.TOP_CENTER);
hbox.getStyleClass().add("hbox1");
Label lblProblem = new Label("Reverse Multiplication Table");
hbox.getChildren().add(lblProblem);
return hbox;
}
public GridPane setUpGrid() {
GridPane pane = new GridPane();
Label[][] labels = new Label[11][11];
for (int row = 0; row < 11; row++) {
for (int col = 0; col < 11; col++) {
Label l = new Label();
setUpLabel(l, col, row);
labels[row][col] = l;
pane.add(l, col, row);
}
}
return pane;
}
public void setUpLabel(final Label l, final int col, final int row) {
l.setPrefHeight(50);
l.setPrefWidth(50);
l.setAlignment(Pos.CENTER);
l.setStyle("-fx-stroke-border: black; -fx-border-width: 1;");
String a = String.valueOf(row);
String b = String.valueOf(col);
if (row == 0 || col == 0) {
l.getStyleClass().add("gridBorders");
if (row == 0) {
l.setText(b);
} else if (col == 0) {
l.setText(a);
}
} else {
l.setText(a + " * " + b);
l.getStyleClass().add("gridInside");
}
}
public List<int[]> showFactors(TextField problem) {
FactorCalculator calc = new FactorCalculator();
int number = Integer.parseInt(problem.getText());
System.out.println(number);
List<int[]> factors = calc.findFactor(number, 10);
System.out.println(factors);
return factors;
}
public static void main(String[] args) {
launch(args);
}
}
GridpaneHelper.java help gridpane node access.
package reversemultiplication;
import javafx.scene.Node;
import javafx.scene.layout.GridPane;
public class GridpaneHelper {
GridPane gridPane;
public GridpaneHelper(GridPane gridPane) {
this.gridPane = gridPane;
}
private int size() {
return gridPane.getChildren().size();
}
public int getColumnSize() {
int numRows = gridPane.getRowConstraints().size();
for (int i = 0; i < gridPane.getChildren().size(); i++) {
Node child = gridPane.getChildren().get(i);
if (child.isManaged()) {
int columnIndex = GridPane.getColumnIndex(child);
int columnEnd = GridPane.getColumnIndex(child);
numRows = Math.max(numRows, (columnEnd != GridPane.REMAINING ? columnEnd : columnIndex) + 1);
}
}
return numRows;
}
public int getRowSize() {
int numRows = gridPane.getRowConstraints().size();
for (int i = 0; i < gridPane.getChildren().size(); i++) {
Node child = gridPane.getChildren().get(i);
if (child.isManaged()) {
int rowIndex = GridPane.getRowIndex(child);
int rowEnd = GridPane.getRowIndex(child);
numRows = Math.max(numRows, (rowEnd != GridPane.REMAINING ? rowEnd : rowIndex) + 1);
}
}
return numRows;
}
public Node[] getColumnChilds(int columnNo) {
if (columnNo < getRowSize()) {
return getChildren()[columnNo];
}
return null;
}
public Node[] getRowChilds(int rowNo) {
Node n[] = new Node[getRowSize()];
if (rowNo <= getRowSize()) {
for (int i = 0; i < getRowSize(); i++) {
n[i] = getColumnChilds(i)[rowNo];
}
return n;
}
return null;
}
public Node[] getChildRowVia() {
Node n[] = new Node[size()];
int col = getColumnSize();
int arrIncre = 0;
for (int i = 0; i < col; i++) {
for (Node n1 : getRowChilds(i)) {
if (n1 != null) {
n[arrIncre] = n1;
arrIncre++;
}
}
}
return n;
}
public Node[][] getChildren() {
Node[][] nodes = new Node[getRowSize()][getColumnSize()];
for (Node node : gridPane.getChildren()) {
int row = gridPane.getRowIndex(node);
int column = gridPane.getColumnIndex(node);
nodes[row][column] = node;
}
return nodes;
}
public Integer postion(Node node, Pos pos) {
if (node != null) {
switch (pos) {
case Row:
return gridPane.getRowIndex(node);
case Column:
return gridPane.getColumnIndex(node);
}
}
return null;
}
enum Pos {
Row,
Column;
}
}
One new method added to FactorCalculator.java class file this help to how many combination are made.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package reversemultiplication;
import java.util.ArrayList;
import java.util.List;
/**
*
* #author reegan
*/
class FactorCalculator {
public List<Integer> list = new ArrayList<Integer>();
private int problem = 0;
public List<int[]> findFactor(int problem, int limit) {
int incrementer = 1;
this.problem = problem;
while (incrementer <= limit) {
if (problem % incrementer == 0) {
list.add(incrementer);
}
incrementer++;
}
return combinational();
}
public List<int[]> combinational() {
List<int[]> arrays = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size(); j++) {
if (list.get(i) * list.get(j) == problem) {
int[] inx = new int[2];
inx[0] = list.get(i);
inx[1] = list.get(j);
arrays.add(inx);
}
}
}
return arrays;
}
}
add your css file in your project ,but this example code not clear in previous set style.after i will tell this.
The answer from Roland/ItachiUchiha is good: here is another approach.
Define an IntegerProperty to hold the current value:
public class Main extends Application {
private final IntegerProperty value = new SimpleIntegerProperty();
// ...
}
Now just have each label observe the value:
public void setUpLabel(final Label l, final int col, final int row) {
value.addListener((obs, oldValue, newValue) -> {
if (col * row == newValue.intValue()) {
l.getStyleClass().add("gridAnswer");
} else {
l.getStyleClass().remove("gridAnswer");
}
});
// all previous code...
}
Finally, just set the value when the button is pressed:
btnFindAnswer.addEventHandler(ActionEvent.ACTION, new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
// you probably don't need this any more:
int x = showFactors(tfProblem);
value.set(Integer.parseInt(tfProblem.getText()));
}
});
So, I am trying to display a chessboard in javaFX. I will have to perform different operations and draw on some of the tiles so I chose to use a Canvas for each tile and a GridPane to arrange them for me in a grid fashion.
Unfortunately I am having some problems with the resizing of the grid tiles; I want my whole chessboard to automatically adapt its size to the Scene. Therefore, I have added a ChangeListener to both the height and width properties of the GridPane which takes care of resizing the tiles. This only works when the window gets bigger, when the window is reduced to a smaller size everything still gets bigger!
Here's the shortest SSCCE I came up with which reproduces my problem:
package chessboardtest;
import javafx.application.Application;
import javafx.beans.value.*;
import javafx.geometry.*;
import javafx.scene.*;
import javafx.scene.canvas.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.stage.Stage;
public class ChessboardTest extends Application {
final int size = 10;
#Override
public void start(Stage primaryStage) {
VBox root = new VBox();
final GridPane chessboard = new GridPane();
fillChessboard(chessboard, size);
ChangeListener<Number> resizeListener = new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> ov, Number t, Number t1) {
double newWidth = chessboard.getWidth() / size;
double newHeight = chessboard.getHeight() / size;
for(Node n: chessboard.getChildren()) {
Canvas canvas = (Canvas)n;
canvas.setWidth(newWidth);
canvas.setHeight(newHeight);
}
}
};
chessboard.widthProperty().addListener(resizeListener);
chessboard.heightProperty().addListener(resizeListener);
root.getChildren().add(chessboard);
root.setPadding(new Insets(10));
VBox.setVgrow(chessboard, Priority.ALWAYS);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("chessboard");
primaryStage.setScene(scene);
primaryStage.show();
}
void fillChessboard(GridPane pane, int size) {
class RedrawListener implements ChangeListener<Number> {
Color color;
Canvas canvas;
public RedrawListener(Canvas c, int i) {
if(i % 2 == 0) {
color = Color.BLACK;
}
else {
color = Color.WHITE;
}
canvas = c;
}
#Override
public void changed(ObservableValue<? extends Number> ov, Number t, Number t1) {
canvas.getGraphicsContext2D().setFill(color);
canvas.getGraphicsContext2D().fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
}
}
for(int row = 0; row < size; row++) {
for(int col = 0, i = row; col < size; col++, i++) {
Canvas c = new Canvas();
RedrawListener rl = new RedrawListener(c, i);
c.widthProperty().addListener(rl);
c.heightProperty().addListener(rl);
pane.add(c, row, col);
}
}
}
public static void main(String[] args) {
launch(args);
}
}
If you don't need a canvas (and you probably don't), just use StackPanes for the squares and make them fill the width and the height. You can always add a canvas (or anything else) to the StackPanes to display their content.
import javafx.application.Application;
import javafx.geometry.HPos;
import javafx.geometry.VPos;
import javafx.scene.Scene;
import javafx.scene.control.Control;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.RowConstraints;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Chessboard extends Application {
#Override
public void start(Stage primaryStage) {
GridPane root = new GridPane();
final int size = 8 ;
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col ++) {
StackPane square = new StackPane();
String color ;
if ((row + col) % 2 == 0) {
color = "white";
} else {
color = "black";
}
square.setStyle("-fx-background-color: "+color+";");
root.add(square, col, row);
}
}
for (int i = 0; i < size; i++) {
root.getColumnConstraints().add(new ColumnConstraints(5, Control.USE_COMPUTED_SIZE, Double.POSITIVE_INFINITY, Priority.ALWAYS, HPos.CENTER, true));
root.getRowConstraints().add(new RowConstraints(5, Control.USE_COMPUTED_SIZE, Double.POSITIVE_INFINITY, Priority.ALWAYS, VPos.CENTER, true));
}
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
This is a nice solution, but resizing is so much easier with data binding in Java FX. You can hide all listener business this way.
Here is a solution much like James D's, but using Rectangles insread of Canvases for the squares:
public class ResizeChessboard extends Application {
GridPane root = new GridPane();
final int size = 8;
public void start(Stage primaryStage) {
for (int row = 0; row < size; row++) {
for (int col = 0; col < size; col++) {
Rectangle square = new Rectangle();
Color color;
if ((row + col) % 2 == 0) color = Color.WHITE;
else color = Color.BLACK;
square.setFill(color);
root.add(square, col, row);
square.widthProperty().bind(root.widthProperty().divide(size));
square.heightProperty().bind(root.heightProperty().divide(size));
}
}
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}