Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

custom table cell renderer in a JTable is not called

843805Apr 19 2006 — edited Apr 19 2006
Hello, all,
I have the following task: I need to select several cells in a column, change the value of those cells, and once the value changes, the color of these cells should change as well. I wrote a custom cell renderer, and registered it for the object type that will use it to render the cell. However, the custom cell renderer is never called. Instead, the class name of the object is displayed in the cell.

My code snippents are as follows:
//Declare the table and add custom cell renderer
JTable table = new JTable (7,7);
table.setCellSelectionEnabled (true);
table.setSelectionMode (ListSelectionModel.SINGLE_INTERVAL_SELECTION);

//Add the custom cell renderer to render objects of type Item
 table.setDefaultRenderer(Item.class, new CustomTableCellRenderer());


//Get the selected cells and change the object type in those cells
//This part works, since I see the app entering the for loop in the debugger, and the item.toString() value is displayed in each selected cell
 int rowIndexStart = table.getSelectedRow();
 int rowIndexEnd = table.getSelectionModel().getMaxSelectionIndex();
 int colIndex = table.getSelectedColumn();

 Item item = new Item ();

 for (int i = rowIndexStart; i<=rowIndexEnd; i++){
              table.setValueAt(item, i, colIndex);
             //I expect the cell to redraw now using custom cell renderer defined below, but that cell render is never called.  Instead, the item.toString() value is displayed in the cell.   What is wrong?
 }


//Definition of custom cell renderer.  
//the getTableCellRendererComponent is never called, since the System.out.println never prints.  I expected this method to be called as soon as the Item object is added to the cell.  Am I wrong in expecting that?

class CustomTableCellRenderer extends DefaultTableCellRenderer  {
    public Component getTableCellRendererComponent (JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
        Component cell = super.getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column);
        System.out.println("value: "+value.getClass()+" isSelected "+isSelected+" hasFocus "+hasFocus+" row "+row+" col "+column);
        if (this.isFocusOwner()) {

        cell.setBackground( Color.red );
        cell.setForeground( Color.white );
        }
        return cell;
    }
}
Please, help,
Thank you!
Elana
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 17 2006
Added on Apr 19 2006
5 comments
441 views