Change back to the default background color in DefaultTableCellRenderer

java swing jtable

37 观看

1回复

6327 作者的声誉

I am reading the following section:

So I decided to write my own custom renderer:

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);
        }
    }
}

I understood how to change the background color to indicate a field with an error in the format. After manual editing by the user, I'd like to have the field reverted back to the original background color. But so far I did not understood how to do it. Can I use DefaultTableCellRenderer in this case ? Should I implement TableCellRenderer .getTableCellRendererComponent instead ?

I was able to get something to display with:

            [...]
            String text = MyFormatter.format(value);
            setBackground(null);
            setForeground(null); // need both to null
            setText(text);

but this breaks the video inverse mode when selecting the row...


Update: I cannot use getBackground() and store the color value in a private member since when editing the background color is Color.blue.

作者: malat 的来源 发布者: 2017 年 12 月 27 日

回应 1


-1

6327 作者的声誉

决定

After much trial-and-errors, here is the only solution I found so far:

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);
    }
}

This is not perfect since the background is displayed as white instead of blue after editing is done. But that's better than the original behavior where the text would not appear after editing is done.

作者: malat 发布者: 2017 年 12 月 28 日
32x32