Generating an N x N grid

2019-01-29 12:30发布

问题:

What is the most painless way to create an N x N grid in a JavaFX application?

The only requirements I'm looking for is that the size of the grid will always take up the same amount of space, so more squares = smaller squares. I can set colors for the squares, and I can hover over each square individually and be able to show some for each square.

I won't know 'N' until the program runs and parses through some data to figure out how many total squares I need which is when I calculate the smallest NxN grid I can use.

From what I can tell my options are:

  1. GridPane - Using the column constraints and row constraints to generate size and possibly add properties for hovering?
  2. TableView - A lot more options for being able to give each cell data to show when hovered over but still difficult to just add rows and columns to start with.
  3. Rectangles - Just generate and draw each rectangle while calculating the x and y coordinates for each square. This will make it easy to do the colors and hovering but I can't see how resizing would work but I'm ok with having a specific size for my application. I'll also have to calculate the best size to make each square to fill up the grids area.

I'm not necessarily looking for someone to code a solution, but if someone has dealt with this and knows a good way I'd like to hear about it.

回答1:

Don't stray away from the original ideas. Why are you looking for "painless" ways when all the methods you've given are all viable? Here's one using your rectangles. The GridMaker.SCREEN_SIZE refers to the size of the screen you must have.

   public static Pane makeGrid(int n){

    double width = GridMaker.SCREEN_SIZE/n;
    Pane p = new Pane();

    Rectangle [][] rec = new Rectangle [n][n];

    for(int i=0; i<n; i++){
        for(int j=0; j<n; j++){
            rec[i][j] = new Rectangle();
            rec[i][j].setX(i * width);
            rec[i][j].setY(j * width);
            rec[i][j].setWidth(width);
            rec[i][j].setHeight(width);
            rec[i][j].setFill(null);
            rec[i][j].setStroke(Color.BLACK);
            p.getChildren().add(rec[i][j]);

        }
    }

    return p;
}

Then simply add the mouse listener to the pane if you wish to make it change color.

 p.setOnMouseClicked(new EventHandler <MouseEvent> (){
        @Override
        public void handle(MouseEvent me){
            double posX = me.getX();
            double posY = me.getY();

            int colX = (int)(posX / width);
            int colY = (int) (posY / width);

            rec[colX][colY].setFill(Color.RED);
        }
    });

-- Edit

1)

2) For Hover, what kind of hover effects are you looking for? You can add Hover effects onto each rectangles, if you want me to show you how, I can definitely code it for you.