Create a JTable with the AbstractTableModel
Each JTable has a model associated with it. You may not realize this but it is created by default when you create the two-dimensional array:Object[][] data = {{1,2,3},{2,3,4},{4,5,6},{7,8,9}}; String[] title= {"Column1", "Column2", "Column3"}; JTable exampleJTable = new JTable (data, columnname)}; |
Fortunately, You can use the JTable object without going through the table template. For example, to find out the method of cell (2, 3), use the method getValueAt:
System.out.println(exampleJTable.getValueAt(2, 2)); |
TableModel byDefault = exampleJTable.getModel(); System.out.println(exampleJTable.getValueAt(2, 2).toString()); |
There are two classes that implement the TableModel interface, DefaultTableModel and AbstractTableModel.
- AbstractTableModel implements the majority of TableModel methods.
- DefaultTableModel is a subclass of AbstractTableModel with three implemented methods whose data is stored in an array.
- public int getRowCount(): Returns the number of lines.
- public int getColumnCount(): returns the number of columns.
- public Object getValueAt(int row, int column): returns the object in the (row, column) box.
Using the AbstractTableModel gives the ability to store the data freely, but you must implement the methods that allow interaction with JTable. The number of methods implemented depends on how the data is managed. To read, only the 3 methods mentioned are sufficient, but to modify (add, delete a row or column), you need to implement other methods to modify the data that is stored in a template of the table.
Creating a table model
class Model extends AbstractTableModel{This code associates the template with the table
private Object[][] data;
private String[] title;
public Model(Object[][] data, String[] title){
this.data = data;
this.title = title;
}
/**
* Returns the column title and the index
*/
public String getColumnName(int col) {
return this.title[col];
}
/**
* Returns the number of columns
*/
public int getColumnCount() {
return this.title.length;
}
/**
* Returns the number of rows
*/
public int getRowCount() {
return this.data.length;
}
/**
* Returns the object at the intersection of row and column
*/
public Object getValueAt(int row, int col) {
return this.data[row][col];
}
/**
* Modify object at row and column intersection
*/
public void setValueAt(Object value, int row, int col) {
this.data[row][col] = value;
}
}
//Creating the JTable JTable table = new JTable(); //Creating the template Model =new Model(data, title); //Link the template to JTable table.setModel(model); |