我有一个 JTable,我想在其中使用自定义背景色突出显示某些行。这是我在下面的类(class)中完成的:
public class MyTable extends JTable {
private List<RefData> data = null;
public List<RefData> getData() {
return data;
}
public void setData(List<RefData> data) {
this.data = data;
}
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component comp = super.prepareRenderer(renderer, row, column);
if (this.data == null || row < 0 || row > this.data.size()-1){
return comp;
}
RefData rowData = this.data.get(row);
if (rowData.getStatus() < 3000){
comp.setBackground(Color.YELLOW);
} else {
comp.setBackground(Color.WHITE);
}
return comp;
}
}
所有这一切就像一个魅力,我得到了我想要的。接下来,在查看生成的 GUI 时,我意识到表格看起来过于紧凑。一切看起来都挤在一起。一如既往地使用默认的 JTable 设置 ;)
好吧,我认为这很容易解决:
myTable.setIntercellSpacing(new java.awt.Dimension(10, 1));
现在,单元格的间距很好但是,添加的单元格边距现在采用默认的表格背景色,在我的例子中是白色。这看起来很难看。
我假设单元格间距增加了单元格边框和 prepareRenderer 返回的组件之间的间距。这将解释结果。但是我怎样才能让它改变单元格本身的背景呢?
我的 prepareRenderer
解决方案是否不适合这项任务?或者有其他解决方案吗?
最佳答案
Border 方法是正确的,但最好是在单元格渲染器中执行,而不是 prepareRenderer()
方法:
JTable.setDefaultRenderer(Object.class, new DefaultCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JComponent component = (JComponent) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
component.setBorder(...);
return component;
}
});
关于java - 在具有自定义行背景颜色的 JTable 中使用 intercellSpacing 会导致意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4122640/