我们如何在GridLayout中显示网格线?
我们如何在GridLayout中显示网格线?在Java中?
JPanel panel = new JPanel(new GridLayout(10,10));
panel.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));
for (int i =0; i<(10*10); i++){
panel.add(new JLabel("Label"));
}
How do we show the gridline in GridLayout? in Java?
JPanel panel = new JPanel(new GridLayout(10,10));
panel.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));
for (int i =0; i<(10*10); i++){
panel.add(new JLabel("Label"));
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我会尝试通过在添加组件时向其添加边框来实现此目的。最简单的方法就是使用BorderFactory.createLineBorder(),如下所示:
但是,这会给单元格之间的边框比面板边缘的边框更厚,因为外边缘只会有一个一像素厚的边框,内部边缘将有两个一像素厚的边框在一起。要解决这个问题,您可以使用
BorderFactory.createMatteBorder()
只在各处绘制一像素宽的边框:这应该为您提供宽度为
borderWidth
的边框,两者之间细胞和沿着外边缘。I would try to do it by adding borders to the components as they are added. The simple way to do it is just using
BorderFactory.createLineBorder()
, like this:However, that will give you thicker borders between the cells than at the edges of the panel, because the outer edges will only have a one-pixel thick border and the inside edges will have two one-pixel thick borders together. To work around that, you can use
BorderFactory.createMatteBorder()
to only draw one-pixel-wide borders everywhere:This should give you borders of width
borderWidth
everywhere, both between cells and along the outside edges.对于 Joe Carnahan 提到的粗边框问题,有一个更简单的解决方法:
GridLayout(10,10, -1, -1)
将组件之间的垂直间隙和水平间隙设置为 -1。所以完整的代码是:There is an easier work around to the thick borders problem mentioned by Joe Carnahan:
GridLayout(10,10, -1, -1)
sets the vertical gaps and the horizontal gaps between components to -1. So the full code is:我找到了一个非常简单的解决方案:
编辑:对于此解决方案,我只需重写 JPanel 的
paint()
方法并手动绘制由GridBagLayout.getLayoutDimensions()
定义的网格在 JPanel 自己的图像之上。I found a very simple solution:
EDIT: For this solution i simply override the
paint()
method of the JPanel and paint the grid as defined byGridBagLayout.getLayoutDimensions()
manually on top of the JPanel's own image.我很想使用 JLayeredPane 在顶部放置一个非不透明组件,根据网格绘制线条。
I would be tempted to use
JLayeredPane
to place a non-opaque component over the top that draws lines based on the grid.或者只需将面板的背景颜色设置为边框颜色,网格线就会像魔法一样出现:
Or just set the background color of the panel to be your border color and the gridlines will appear like magic: