Java 在DefaultTableCellRenderer中更改回默认背景色

Java 在DefaultTableCellRenderer中更改回默认背景色,java,swing,jtable,Java,Swing,Jtable,我正在阅读以下章节: 因此,我决定编写自己的自定义渲染器: public class MyRenderer extends DefaultTableCellRenderer { @Override protected void setValue(Object value) { try { String text = MyFormatter.format(value); //setBackground(Color

我正在阅读以下章节:

因此,我决定编写自己的自定义渲染器:

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);
        }
    }
}
我了解了如何更改背景颜色以指示格式中有错误的字段。在用户手动编辑后,我希望将字段恢复为原始背景色。但到目前为止我还不知道该怎么做。在这种情况下我可以使用吗?我应该实施吗

我能够得到一些东西来展示:

            [...]
            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);
    }
}

这并不完美,因为编辑完成后背景显示为白色而不是蓝色。但这比编辑完成后文本不会出现的原始行为要好。

setBackground(null)getBackground()
保留引用),然后在需要将颜色恢复为原始颜色时使用该引用?再次
setBackground(null)应该可以工作。如果它不起作用,那么请发布你的程序代码,这样我们就可以自己测试你的代码。谢谢你的编辑,但我们需要的是一个MCVE。否则恐怕我们只能同情你了。请阅读链接。只是重申:请在MCVE中编辑,否则您可能无法获得所需的帮助@HoverCraftFullOfels,是否将背景设置为父级颜色,而不是组件的初始/原始颜色?“如果此参数为null,则此组件将继承其父级的背景色”(来自
组件#setBackground