Java TableCellRenderer create renderer based on JComponent

Description

Java TableCellRenderer create renderer based on JComponent

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

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;


class MyDefaultTableModel extends DefaultTableModel {
   //from www .ja v  a2  s.co m

   public Class getColumnClass(int mColIndex) {
     int rowIndex = 0;
     Object o = getValueAt(rowIndex, mColIndex);
     if (o == null) {
       return Object.class;
     } else {
       return o.getClass();
     }
   }
 }
public class Main extends JPanel {
   public Main() {
      setLayout(new BorderLayout(5, 5));
      DefaultTableModel model = new MyDefaultTableModel();
      
      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());
      
      JScrollPane sp = new JScrollPane(table);

      add(sp, BorderLayout.CENTER);
   }
   public static void main(String[] args) {
      JFrame frame = new JFrame("java2s.com");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      Main m = new Main();
      frame.add(m);
      frame.setSize(300, 210);
      frame.setVisible(true);
   }
}
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);
   }
 }



PreviousNext

Related