Swing : Use JTable to display a List of Objects



Delicious
Consider I have a class Word_Analysis which contains following parameters.

class Word_Analysis {

boolean isAllCap;
String word;
int length;
boolean isInitialCap;
boolean isRoman;
boolean isDigit;
//create getter and setters
}

To display the records of Entity objects , an object of DetaultTableModel has to be created and set it to table. Some methods need to be overloaded and its mandatory to do it. Below code is the minimum methods required.

class TableModel extends AbstractTableModel{

List wordsList;
String headerList[] = new String[]{“Col1”,”Col2”,”Col3”,”Col4”,”Col5”};

public TableModel(List list) {
wordsList = list;
}

@Override
public int getColumnCount() {
return 5;
}

 

@Override
public int getRowCount() {
return wordsList.size();
}

// this method is called to set the value of each cell
@Override
public Object getValueAt(int row, int column) {
Word_Analysis entity = null;
entity= wordsList.get(row);

switch (column) {

case 0:
return entity.word;
case 1:
return entity.length;
case 2:
return entity.isAllCap();
case 3:
return entity.isIntialCap();
case 4:
return entity.isDigit();
case 5:
return entity.isRoman();

default :

return "";
}


 //This method will be used to display the name of columns
public String getColumnName(int col) {
return headerList[col];
}
}

Once the model class is created create the model object and set it to table

public class DisplayTable{
public static void main(String args[]){
List entityList = new ArrayList();
//set the entity objects in the list
JFrame frame = new JFrame();
JTable table = new JTable();
DefaultTableModel model = new TableModel(entityList);
JScrollPane scrollPane = new JScrollPane(table);
table.setModel(model);
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);

frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}