JTable renderer to check old/new cell values then set color

I feel there are many broken designs, and a few working designs.

If the requirement is needed only upon user input (not during background update like MOM), then property change event or cell editor could probably pass old/new values to cell renderer.

But let’s assume the requirement is that all changes (by user or behind the scene) be covered. Now, how many ways can the underlying data change? Only 2 — Either by setValueAt() or by direct write to underlying. So I’d make underlying data structure (usually 2D) private and provide a setter as a single choke point. In this setter I would save old value into another 2D. Cell renderer has access to the jtable, so it can retrieve the table model, and access the other 2D.

Note you have to install your render as default for Integer.class (not Object.class) if the column is integer.

Note you must save the default background colour early. That color object is a field of the renderer instance. The same renderer instance is reused and persisted. Once you call renderer.setBackground(), that field is changed forever (and the previos color object unreachable), so you must save the before-value.

What if we force all updates to go through setValueAt(), including MOM updates? Heavy load on EDT given the high volume of MOM. Hard truth — Some updates to model must happen off EDT. However, fireXXX() must always run on EDT. [[java concurrency]] says “data  model  fireXxx  methods always call  the model listeners directly rather than submitting a new event to the event queue, so the fireXxx methods must be called only from the event thread.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s