Generating an N x N grid

前端 未结 1 580
一个人的身影
一个人的身影 2020-12-22 05:34

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 u

相关标签:
1条回答
  • 2020-12-22 06:22

    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.

    0 讨论(0)
提交回复
热议问题