Creating a Class-Based Custom Cell Renderer in a JTable Component - Java Swing

Java examples for Swing:JTable Cell

Description

Creating a Class-Based Custom Cell Renderer in a JTable Component

Demo Code


import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;

import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;

public class Main {
  public static void main(String[] argv) {
    DefaultTableModel model = new DefaultTableModel() {

      public Class getColumnClass(int mColIndex) {
        int rowIndex = 0;
        Object o = getValueAt(rowIndex, mColIndex);
        if (o == null) {
          return Object.class;
        } else {/* www.  j a  v a  2  s  . c  o  m*/
          return o.getClass();
        }
      }
    };
    JTable table = new JTable(model);

    // Add data
    model.addColumn("Col1", new Object[] { Color.red });
    model.addRow(new Object[] { Color.green });
    model.addRow(new Object[] { Color.blue });

    table.setDefaultRenderer(Color.class, new ColorTableCellRenderer());
  }

}

class ColorTableCellRenderer extends JComponent implements TableCellRenderer {
  Color curColor;
  public Component getTableCellRendererComponent(JTable table, Object value,
      boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
    if (curColor instanceof Color) {
      curColor = (Color) value;
    } else {
      // If color unknown, use table's background
      curColor = table.getBackground();
    }
    return this;
  }

  // Paint current color
  public void paint(Graphics g) {
    g.setColor(curColor);
    g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
  }
}

Related Tutorials