我们如何在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"));
}
最佳答案
我会尝试通过向组件添加边框来做到这一点。简单的方法就是使用BorderFactory.createLineBorder()
,如下所示:
JPanel panel = new JPanel(new GridLayout(10,10));
panel.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));
for (int i =0; i<(10*10); i++){
final JLabel label = new JLabel("Label");
label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
panel.add(label);
}
但是,这将使您在单元格之间的边框比在面板的边缘处更粗,因为外部边缘将仅具有一个像素的粗边框,而内部边缘将具有两个一像素的粗边框。要解决此问题,您可以使用
BorderFactory.createMatteBorder()
在所有位置仅绘制一个像素宽的边框:final int borderWidth = 1;
final int rows = 10;
final int cols = 10;
JPanel panel = new JPanel(new GridLayout(rows, cols));
panel.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
final JLabel label = new JLabel("Label");
if (row == 0) {
if (col == 0) {
// Top left corner, draw all sides
label.setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
else {
// Top edge, draw all sides except left edge
label.setBorder(BorderFactory.createMatteBorder(borderWidth,
0,
borderWidth,
borderWidth,
Color.BLACK));
}
}
else {
if (col == 0) {
// Left-hand edge, draw all sides except top
label.setBorder(BorderFactory.createMatteBorder(0,
borderWidth,
borderWidth,
borderWidth,
Color.BLACK));
}
else {
// Neither top edge nor left edge, skip both top and left lines
label.setBorder(BorderFactory.createMatteBorder(0,
0,
borderWidth,
borderWidth,
Color.BLACK));
}
}
panel.add(label);
}
}
这应该为您提供到单元格之间以及沿外部边缘的各处
borderWidth
宽度的边界。