Java JTable use default cell editor

Description

Java JTable use default cell editor

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

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

class MyDefaultTableModel extends DefaultTableModel {

   public Class getColumnClass(int columnIndex) {
      Object o = getValueAt(0, columnIndex);
      if (o == null) {
         return Object.class;
      } else {//from  w ww  . ja va  2s .  c  o m
         return o.getClass();
      }
   }
};

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

      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.png") });
      model.addColumn("Number", new Object[] { new Integer(1) });
      model.addColumn("Object", new Object[] { "object" });

      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      frame.add(new JScrollPane(table));
      frame.setLocationByPlatform(true);
      frame.pack();
      frame.setVisible(true);
   }

}



PreviousNext

Related