Home > java, swing > Use enum to define JTable columns

Use enum to define JTable columns

November 26th, 2008

Last week while tediously defining another Swing TableModel, I had a little epiphany. Typically, I’d define column headers, types, etc with a list of integer constants, and some arrays:

public class MyTableModel extends AbstractTableModel
{
    private final int NAME_COLUMN = 0;
    private final int VALUE_COLUMN = 1;
 
    private final String NAMES[] = { "Name", "Value" };
    private final Class CLASSES[] = { String.class, Double.class };

    . . .

   public String getColumnName(int columnIndex)
   {
      return NAMES[columnIndex];
   }

   . . .
}

This code is pretty tedious to maintain. In particular, switching column order involves a bunch of changes that are easy to get wrong. How about this instead… use an enum to define the columns!!

public class MyTableModel extends AbstractTableModel
{
    private static enum Columns
    {
        Name(String.class), Value(Double.class);

        final Class klass;

        Columns(Class klass)
        {
             this.klass = klass;
        }
    }

    . . .

   public int getColumnCount() { return Columns.values().length; }

   public Class getColumnClass(int columnIndex)
   {
      return Columns.values()[columnIndex].klass;
   }

   public String getColumnName(int columnIndex)
   {
      return Columns.values()[columnIndex].toString();
   }

   . . .
}

Now rearranging column order just works. Furthermore, you can add whatever column-specific functionality you like as methods on the enum. I think this approach can be generified with an interface for the enum to implement and a new abstract table model base class that can handle all the boilerplate above (getColumnCount(), getColumnName(), etc). When I get around to trying it out, I’ll post an update.

Late breaking: Of course, a quick search reveals I’m not the first person to think of this. Typical.

java, swing ,

  1. No comments yet.
  1. No trackbacks yet.