This time I will talk about a custom jtable I developed in order to have the simplest way to show READ ONLY data.
First how I was coding before:
class Person{
String firstName;
String lastName;
/*..*/
}
DefaultTableModel dtm= new DefaultTableModel();
for(Person p: getListPersons()){
Dtm.add(new Object[]{p.getFirstName(),p.getLastName()});
}
Dtm.addColumn(“firstName”);
Dtm.addColumn(“lastName”);
JTable table=new JTable();
table.setModel(dtm);
And to know which Object is currently selected:
Int index=table.getSelectedIndex();
Int modelIndex=table.convertRowIndexToModel(index);
Person selected=getListPersons.get(modelIndex);
After coding this way too many time I wondered:
As we only show only one kind of object in the table, wouldn’t it be easier:
to have a table of T
to be able to add/remove a T
to be able to get the selected T
All this without coding a custom JTable or/and TableModel each time
So the plan is to have an easy way to
-Define the class of objects to show using the JTable
-Define the columns
-Add/remove an object from the table
-Get the selected objects
So now let’s see the implementation I called BeanReaderJTable
First we need a generic parameter
public class BeanReaderJTable<T> extends JTable {/*…*/}
The contructor take the field names and the column names you want as header value.
public BeanReaderJTable(String[] fields, String[] title)
Adding/removing a row or getting the selected objects can’t be easier:
addRow(T)
addRow(T[])
addRow(Collection<T>)
removeRow(T)
getSelectedObject():T
getSelectedObjects():T[]
What is doing the actual job is the GenericTableModel.
The important job is done in getValueAt(int,int). The reflexion API is used to retrieve the value of a given pair field+row
Now let’s see a sample:
// declare the type + fields+column title
String[] fields = new String[] { "size", "size.width", "size.height", "class", "visible", null };
String[] titles = new String[] { "size", "width", "height", "class", "is visible", null };
BeanReaderJTable<Component> table = new BeanReaderJTable<Component>(fields, titles);
//populate the table
table.addRow(getAllComponents(frame));
You may have noticed, I left the last field empty, doing so, an empty column is created that can be used to set for example a button cell editor
And also what you can see, is that you can access nested field like size.width
This time you should actually be able to access the code source repository, my java.net project has been approved:
BeanReaderJTable