【发布时间】:2016-06-16 17:37:07
【问题描述】:
我正在尝试将 JTable 显示为网格,单元格之间有线条。不过,我只能在单个单元格中添加边框,这看起来并不正确;如果我添加完整的边框,我会得到一堆不连贯的盒子,这看起来很丑陋和错误。使用 MatteBorders(如下面的代码)看起来会好一些,但会导致边界线不太相交的间隙。
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component stamp = super.prepareRenderer(renderer, row, column);
int top = 1;
int left = 1;
int bottom = row == 7 ? 1 : 0; //Grid is always 8x8, this ensures the bottom/right will have full borders.
int right = column == 7 ? 1 : 0;
MatteBorder border = new MatteBorder(top, left, bottom, right, Color.BLACK);
if (stamp instanceof JComponent) {
((JComponent) stamp).setBorder(border);
}
return stamp;
}
我觉得必须有一些方法可以正确地做到这一点,这样我就可以在单元格元素之间获得网格线。我错过了什么?如果不出意外,有没有办法让 MatteBorder 跨越间隙,或者将正常边框稍微推远一点,以便相邻单元格的边框重叠?
编辑:可以使用 setShowGrid(true) 和 setGridColor(Color.BLACK)。
【问题讨论】:
-
你试过
table.setShowGrid(true);? -
@whiskeyspider 那没有用,但我做了更多的挖掘并弄清楚了原因 - 它只是默认为每个单元格所需的相同背景颜色。那 + setGridColor() 解决了,谢谢。
-
默认行为是在单元格之间有网格线。阅读 How to Use Tables 上的 Swing 教程中的部分。
-
@camickr 是的,我刚刚意识到我没有看到它们,因为它们的颜色与背景相同。