AbstractTableModel tutorial

Vagelism picture Vagelism · Mar 23, 2012 · Viewed 18.2k times · Source

I am working on a project that needs to show some data on a jtable. I found many tutorials about jtables but few on how to customise a AbstractTableModel, the most parts are ready code. Even in Oracle's page I found this general jtable tutorial, but few information for AbstractTableModel and how to make a customized model.Oracle Jtable Tutorial I am new to programing so will be apriciate a tutorial for my level of skils. Thank you in advanced.

Answer

lanoxx picture lanoxx · Apr 26, 2012

The AbstractTableModel contains three methods that need to be overwritten. These are:

public int getRowCount();
public int getColumnCount();
public Object getValueAt(int row, int column);

The JTable uses these methods to find out how many fields (rows and columns) there are and to get the value (as type Object) of each field. When you overwrite these methods it is up to you which kind of data type you want to use. For example you can use a two dimensional Object array:

Object[][] data;

or an ArrayList of arrays:

List<Object[]> data = new ArrayList<Object[]>();

The fixed sized array might be easier to use but it is more difficult do dynamically add values. Of course you can also use Maps or other data structures. You just need to adjust your implementation of the three methods above to return the proper information from your data structure, such as how many rows your model currently contains, etc.

There are also a couple more methods that can be overwritten but don't have to. For example, if you want to have custom column names you must additionally overwrite the public String getColumnName(int col) method.

For example like this:

private static final String[] COLUMN_NAMES = {"User", "Password", "Age"};
public String getColumnName(int col) {
    return COLUMN_NAMES[col];
}

Look at the Javadoc for AbstractTableModel to get an overview of other methods that can be overwritten.

If you want to be able to change the Data in your TableModel then you need to overwrite the setValueAt method (if I am not mistaken):

void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    //depending on your data structure add the aValue object to the specified
    //rowIndex and columnIndex position in your data object
    //notify the JTable object:
    fireTableCellUpdated(row, col);
}

Important: Whenever you add or remove a row, then the respective function in your TableModel implementation must call the respective fireTableRowsInserted (or deleted) function. Otherwise you will see strange visual effects happen to your JTable:

public void addRow(Object[] dates) {
    data.add(dates);
    int row = data.indexOf(dates);
    for(int column = 0; column < dates.length; column++) {
        fireTableCellUpdated(row, column);
    }
    fireTableRowsInserted(row, row);
}