![](/img/trans.png)
[英]custom DefaultTableCellRenderer not changing the background color of row on jTable
[英]Change back to the default background color in DefaultTableCellRenderer
我正在阅读以下部分:
所以我决定编写自己的自定义渲染器:
public class MyRenderer extends DefaultTableCellRenderer {
@Override
protected void setValue(Object value) {
try {
String text = MyFormatter.format(value);
//setBackground(Color.white); // my text becomes invisible
//setBackground(null); // my text becomes invisible
setBackground(???);
setText(text);
} catch (IllegalArgumentException e) {
// Something is not quite right, indicate the error to the user:
setBackground(Color.red); // at this point in time getBackground() returns Color.blue
super.setValue(value);
}
}
}
我了解如何更改背景颜色以指示格式错误的字段。 用户手动编辑后,我希望该字段恢复为原始背景颜色。 但到目前为止,我还不明白该怎么做。 在这种情况下我可以使用DefaultTableCellRenderer
吗? 我应该实现TableCellRenderer .getTableCellRendererComponent
吗?
我能够得到一些东西来显示:
[...]
String text = MyFormatter.format(value);
setBackground(null);
setForeground(null); // need both to null
setText(text);
但这在选择行时打破了视频反转模式......
更新:我不能使用getBackground()
并将颜色值存储在私有成员中,因为编辑背景颜色时是Color.blue
。
经过多次反复试验,这是我迄今为止找到的唯一解决方案:
protected void setValue(Object value) {
try {
String text = MyFormatter.format(value);
if (errorState) {
updateUI(); // call setBackground(null) and properly repaint()
errorState = false;
}
setText(text);
} catch (IllegalArgumentException e) {
// store error state:
errorState = true;
// Something is not quite right, indicate the error to the user:
setBackground(Color.red);
super.setValue(value);
}
}
这并不完美,因为编辑完成后背景显示为白色而不是蓝色。 但这比编辑完成后文本不会出现的原始行为要好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.