How to draw grid using swing class Java and detect mouse position when click and drag

后端 未结 3 1425
醉酒成梦
醉酒成梦 2020-12-01 04:49

I am trying to create a grid UI (5*5) using Swing classes. I tried a nested loop and adding a jPanel dynamically to the jFrame. And I also tried to change the background col

3条回答
  •  情歌与酒
    2020-12-01 05:24

    I did not like rendering of borders since inside the grid some were duplicated if there were more than the example. I think that this solution is better:

    private int width;
    private int height;
    
    // ...
    
    for (int row = 0; row <= this.height; row++) {
        for (int col = 0; col <= this.width; col++) {
            gbc.gridx = col;
            gbc.gridy = row;
    
            CellPane cellPane = new CellPane();
            Border border = new MatteBorder(1, 1, (row == this.height ? 1 : 0), (col == this.width ? 1 : 0), Color.GRAY);
    
            cellPane.setBorder(border);
            this.add(cellPane, gbc);
        }
    }
    

    Edit:

    My solution is better, because if the original code will be 5x5 cells, but more, such as 10x10 ... inner edges of some cells will be in contact and to create some places thick grid. It's nice to see on the screenshot thick grid

提交回复
热议问题