在 DefaultTableCellRenderer 中改回默认背景色
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
in this case ? Should I implement 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);
}
}
这并不完美,因为背景在编辑完成后显示为 white 而不是 blue。但这比编辑完成后文本不会出现的原始行为要好。
我正在阅读以下部分:
所以我决定编写自己的自定义渲染器:
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
in this case ? Should I implement 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);
}
}
这并不完美,因为背景在编辑完成后显示为 white 而不是 blue。但这比编辑完成后文本不会出现的原始行为要好。