Basically, I'm writing a little date-picker widget for part of an app I'm building:

When you click a cell in the table it goes green, as shown above. When you click a different cell it goes back to its default color as expected and the new cell goes green. However, if you click away from the entire table and onto something like a JButton all the cells just go back to their default colors, when what I'd like to happen is have the currently selected cell stay green (so it's visible while the user does other things).
Here's the renderer I wrote to do it. I can see *why* it doesn't work, however, I can't see an obvious solution right now
Code: Select all
/**
* Manages the rendering of the cells in the calendar
*/
package org.w3style.calendar;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
/**
* This is just a basic extension of the DefaultTableCellRender from the current L&F
*/
public class CalendarCellRenderer extends DefaultTableCellRenderer
{
/**
* The current row being rendered
*/
protected int row;
/**
* The current column being rendered
*/
protected int col;
/**
* If this cell is part of the "selected" row
*/
protected boolean isSelected;
/**
* If this cell is in focus (the one clicked upon)
*/
protected boolean isFocused;
/**
* Fetch the component which renders the cell ordinarily
* @param JTable The current JTable the cell is in
* @param Object The value in the cell
* @param boolean If the cell is in the selected row
* @param boolean If the cell is in focus
* @param int The row number of the cell
* @param int The column number of the cell
* @return Component
*/
public Component getTableCellRendererComponent(JTable tbl, Object v, boolean isSelected, boolean isFocused, int row, int col)
{
//Store this info for later use
this.row = row;
this.col = col;
this.isSelected = isSelected;
this.isFocused = isFocused;
//and then allow the usual component to be returned
return super.getTableCellRendererComponent(tbl, v, isSelected, isFocused, row, col);
}
/**
* Set the contents of the cell to v
* @param Object The value to apply to the cell
*/
protected void setValue(Object v)
{
super.setValue(v); //Set the value as requested
//Set colors dependant upon if the row is selected or not
if (!this.isSelected) this.setBackground(new Color((float)0.87, (float)0.91, (float)1.0));
else this.setBackground(new Color((float)0.75, (float)0.78, (float)0.85));
//Set a special highlight color if this actual cell is focused
if (this.isFocused) this.setBackground(new Color((float)0.5, (float)0.80, (float)0.6));
}
}
Cheers,
Chris