ObjectTableModel

Top  Previous  Next

 

ObjectTableModel is a ListTableModel whose data is a collection of arbitrary Java Objects. This abstract class uses an internal ArrayList structure to store the rows of a JTable. Subclasses should implement the methods:

 

public Object getValueAt(Object rowObject, int index);

public void setValueAt(Object rowObject, Object aValue, int index);

 

, which define how objects at a column index are retrieved/set respectively.

These methods should preferrably cast the supplied Object argument to an appropriate class type, and use the index parameter to get to the actual cell value.

 

Also, the column names are specified in the constructor, or with the method:

 

public void setColumns(String[] columnNames);

 

Example: Make an ObjectTableModel for the object Employee given below:

 

public class Employee {

       public String firstName;

       public String lastName;

       public Integer age;

       Employee(String firstName, String lastName, int age) {

               this.firstName = firstName;

               this.lastName = lastName;

               this.age = new Integer(age);

       }

}

 

public class IDTableModel exends ObjectTableModel {

       public IDTableModel() {

               super(new String[]{"First Name", "Last Name", "Age"});

       }

       public Object getValueAt(Object o, int index) {

               Employee emp = (Employee) o;

               Object ret = null;

               switch (index) {

                       case 0: {

                               ret = emp.firstName;

                               break;

                       }

                       case 1: {

                               ret = emp.lastName;

                               break;

                       }

                       case 2: {

                               ret = emp.age;

                               break;

                       }

               }

               return ret;

       }

       public void setValueAt(Object o, Object aValue, int index) {

               Employee emp = (Employee) o;

               switch (index) {

                       case 0: {

                               emp.firstName = value.toString();

                               break;

                       }

                       case 1: {

                               lastName = value.toString();

                               break;

                       }

                       case 2: {

                               emp.age = Integer.valueOf(value.toString());

                               break;

                       }

               }

       }

}