Using Built-In Cell Renderers and Editors in a JTable Component - Java Swing

Java examples for Swing:JTable Cell

Description

Using Built-In Cell Renderers and Editors in a JTable Component

Demo Code


import java.util.Date;
import java.util.Enumeration;

import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

public class Main {
  public void main() {
    DefaultTableModel model = new DefaultTableModel() {

      public Class getColumnClass(int columnIndex) {
        Object o = getValueAt(0, columnIndex);
        if (o == null) {
          return Object.class;
        } else {//from   w w w  .  j  av a 2s  .com
          return o.getClass();
        }
      }
    };
    JTable table = new JTable(model);

    // Add a column for each of the available renderers
    model.addColumn("Boolean", new Object[] { Boolean.TRUE });
    model.addColumn("Date", new Object[] { new Date() });
    model.addColumn("Double", new Object[] { new Double(Math.PI) });
    model.addColumn("Float", new Object[] { new Float(1.2) });
    model.addColumn("Icon", new Object[] { new ImageIcon("icon.gif") });
    model.addColumn("Number", new Object[] { new Integer(1) });
    model.addColumn("Object", new Object[] { "object" });

    int mColIndex = 0;
    findTableColumn(table, mColIndex).setCellRenderer(
        table.getDefaultRenderer(Boolean.class));
    findTableColumn(table, mColIndex).setCellEditor(
        table.getDefaultEditor(Boolean.class));

  }

  public TableColumn findTableColumn(JTable table, int columnModelIndex) {
    Enumeration e = table.getColumnModel().getColumns();
    for (; e.hasMoreElements();) {
      TableColumn col = (TableColumn) e.nextElement();
      if (col.getModelIndex() == columnModelIndex) {
        return col;
      }
    }
    return null;
  }
}

Related Tutorials