Search code examples
javaswingjtablecelltablecellrenderer

How to make a row in JTable with 367 cells where only the first one has text and the rest have colors


I am working on a color based database program that shows bookings inside an accommodation based on color. the problem I've been having is that the table has 367 columns (the name of the accommodation and then all days of a year.) the problem I've been having is that I can't figure out how to make the first column of the row display a string and the rest a color.

I made a basic renderer that should display colors but I don't know how to use it.

public class MyRenderer extends DefaultTableCellRenderer{
   public Component getTableCellRendererComponent(JTable table, Object value, boolean   isSelected, boolean hasFocus, int row, int column) 
   {
       Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); 
       if (! table.isRowSelected(row))
       { 
           if(row == 2 && column == 2)
               c.setBackground(new java.awt.Color(0, 0, 255));
           else
               c.setBackground(table.getBackground());  
       } 
       return c;
   } 
}

how would I integrate this with a JTable?

PS I have a header I want to show but the rows should be empty to begin with. then when a button is pressed it should add a row. this last button I can make myself I just need help with the cellrenderer

At the moment my JTable is initialized like this: JTable table = new JTable();

Does anybody have any tips?


Solution

  • I suppose there is two state for a day, booked or not. So the value is boolean. You can set renderers by class types. For example:

    table.setDefaultRenderer(Boolean.class, new MyRenderer());
    

    With that, your renderer will be uses only if value is a boolean.

    public class MyRenderer extends DefaultTableCellRenderer{
       public Component getTableCellRendererComponent(JTable table, Object value, boolean   isSelected, boolean hasFocus, int row, int column) 
       {
           Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); 
    
               if(value)
                   c.setBackground(/*Color for booked days*/ );
               else
                   c.setBackground(table.getBackground());  
    
           return c;
       } 
    }