AbstractTableModel tutorial

I am working on a project that needs to show some data on a jtable. I found a lot of jtables tutorials, but a little on how to set up AbstractTableModel, most of the parts are code ready. Even on the Oracle page I found this generic jtable tutorial, but little information for AbstractTableModel and how to create a custom model. Oracle Jtable Tutorial I'm new to programming, so the tutorial for my skins level will be ugly. Thank you for your promotion.

+3


source to share


1 answer


AbstractTableModel contains three methods that need to be overwritten. It:

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

      

JTable uses these methods to determine the number of fields (rows and columns) and to retrieve the value (as of type Object) of each field. When you rewrite these methods, it is up to you to decide what type of data you want to use. For example, you can use a two-dimensional array of objects:

Object[][] data;

      

or ArrayList of arrays:

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

      

A fixed size array may be easier to use, but it is more difficult to dynamically add values. Of course, you can also use Maps or other data structures. You just need to tweak the implementation of these three methods to return the correct information from your data structure, like how many rows your model contains, etc.

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

.



For example, like this:

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

      

Take a look at the Javadoc for AbstractTableModel for an overview of other methods that might be overridden.

If you want to change the data in your TableModel, you need to rewrite the method setValueAt

(if I'm 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, the corresponding function in your TableModel implementation must call the corresponding fireTableRowsInserted (or deleted) function. Otherwise, you will see strange visuals with 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);
}

      

+19


source







All Articles