Is this your first time here? SwingWiki is a Java Swing Developer community site with an big archive of Swing-related usenet groups and mailing lists, but also tips, tricks and articles and book reviews written by your colleagues from around the world. If you came here through a search engine and did not find what you were looking for, make sure to check the wiki table of contents.

Different row colors for JTable

To show only a single row of JTable in a different color (background or foreground), create a custom table renderer that will initialize the colors before delegating work to the DefaultRenderer1)

   private class RowColorRenderer extends DefaultTableCellRenderer
   {
     public Component getTableCellRendererComponent(JTable table, Object value,
                          boolean isSelected, boolean hasFocus, int row, int column)
      {
        Object topVal=table.getValueAt(0,column);
        int i=0;
        if (topVal instanceof Integer)
        {
          i=((Integer)topVal).intValue();
        }
        if (isSelected||(i==0))
          {
              this.setBackground(Color.white);
              this.setForeground(Color.black);
          }
        else
          {
            this.setBackground(Color.red);
            this.setForeground(Color.white);
          }
        return super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
      }
   }

To set up the renderer for a table, use :

xt.setDefaultRenderer(java.lang.String.class,new RowColorRenderer());
1) alternatively, read the current renderer of the table and embed it into a private field, and then delegate work to it
 

Comments? Corrections? Contact us or Login to edit pages directly (registration is free and takes less than displaying a JLabel)
  howto/jtable_row_color.txt · Last modified: 2005/02/12 17:59
 
Recent changes | RSS changes | Table of contents | News Archive | Terms And Conditions | Register | The Quest For Software++| Ruby Resources

Sedo - Buy and Sell Domain Names and Websites project info: swingwiki.org Statistics for project swingwiki.org etracker� web controlling instead of log file analysis