生成N x N网格 [英] Generating an N x N grid
问题描述
在JavaFX应用程序中创建N x N网格的最简单方法是什么?
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.
我不会知道'N'直到程序运行并解析一些数据,以计算出我需要多少总方格,这是我计算可以使用的最小NxN网格时。
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:
- GridPane - 使用列约束和行约束生成大小并可能添加悬停属性?
- TableView - 有更多选项可以让每个单元格数据在悬停时显示,但仍然很难只添加行和列。
- 矩形 - 只需生成并绘制每个矩形,同时计算每个方块的x和y坐标。这样可以很容易地进行颜色和悬停,但我看不出调整大小是如何工作的,但我可以为我的应用程序设置特定的大小。我还必须计算最佳尺寸,以使每个方格填满网格区域。
我不一定要找对于某人编写解决方案的代码,但是如果有人处理了这个问题,并且知道一个好的方法我想听听它。
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.
推荐答案
不要偏离原来的想法。当你给出的所有方法都可行时,你为什么要寻找无痛的方式?这是使用矩形的一个。 GridMaker.SCREEN_SIZE指的是您必须拥有的屏幕大小。
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);
}
});
- 编辑
1)< a href =https://i.stack.imgur.com/DakDX.png =nofollow noreferrer>
2)对于悬停,你在寻找什么样的悬停效果?你可以在每个矩形上添加悬停效果,如果你想让我告诉你如何,我绝对可以为你编码。
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.
这篇关于生成N x N网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!