我会尝试通过在添加组件时向它们添加边框来做到这一点。执行此操作的简单方法是使用 ,如下所示: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