我会尝试通过添加边框添加组件来做到这一点.简单的方法是使用BorderFactory.createLineBorder(),像这样:
JPanel panel = new JPanel(new GridLayout(10,10));
panel.setBorder(BorderFactory.createEmptyBorder(2,2,2,2));
for (int i =0; 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无处不在,单元格之间和外边缘.