Reputation: 1045
I am learning on how to use JTables in Swing. I have already figured out to connect to a database and retrieve the resultset. I am also able to display the data by using the first option (see below).
a) I want to make sure I am understanding the idea of using/passing a TableModel versus directly passing the rows and columns is to have the ability to use built in methods that are available in AbstractTableModel; DefaultTableModel and ListTableModel classes.
b) What is a custom TableModel?
So far I have come across 4 ways:
ex:
JTable tab = new JTable(Object [][] rows, Object[] cols);
2. Create a table model from a class that implements AbstractTableModel.
ex:
MyModel model = new MyModel(Object[][] obj1, String[] header);
//MyModel is a class that extends AbstractTableModel.
//MyModel has an ArrayList<Object[]> to store obj1[]
//MyModel implements getRowCount(), getColumnCount() and
getValueAt(int rowIndex, int columnIndex) and also getColumnName(int index)
JTable tab = new JTable(model);
3.Create a table model from a class that implements DefaultTableModel.
ex:
DefaultTableModel model = new DefaultTableModel(String data[][],String col[]);
(or)
DefaultTableModel model = DefaultTableModel(Vector data, Vector columnNames)
JTable table = new JTable(model);
4.ListTableModel
Upvotes: 1
Views: 7989
Reputation: 533
When you directly pass your data, the JTable will create a DefaultTableModel internally which you can get by calling table.getModel()
.
Different TableModels have different features and you can implement your own by creating a class that implements TableModel or extends AbstractTableModel (or DefaultTableModel). The idea behind this is that you sometimes need more than just the raw table data.
For example if you want to attach an Object to each row:
You could write a TableModel that holds an object per row and provides methods like Object getObject(int rowIndex)
and void setObject(int rowIndex, Object object)
.
To do so you would hold an extra array or list inside your TableModel that contains the objects and is always of the same size as the amount of rows.
Another reason could be that the tablemodel loads row data while you scroll or that you want display data from several data sources dynamically.
A TableModel doesn’t necessarily have to hold the data, it just provides it to the JTable.
Upvotes: 3