How to subclass DefaultTableModel and change its dataVector
I want to extend the DefaultTableModel and change its dataVector. I want to make the dataVector to show only specific fields of DataHolder in the column:
public class MyTableModel extends DefaultTableModel {
/**
* The data vector
*/
private Vector<DataHolder> dataVector_;
//overridden method to add row in the table model
public void addRow(DataHolder rowData) {
insertRow(getRowCount(), rowData);
}
public void insertR开发者_如何转开发ow(int row, DataHolder rowData) {
dataVector_.insertElementAt(rowData, row);
fireTableRowsInserted(row, row);
}
...} //end of MyTableModel
class DataHolder{
private int age;
private int year;
private int month;
private int day;
}
How can i display specific DataHolder fields in my jtable? My table has 3 columns for month, day, and year.
You need to create a custom model for this. The DefaultTableModel is not the best place to start.
Generally you would extend AbstractTableModel and use an ArrayList to store your DataHolder Objects. Then you need to implement the other methods of the TableModel interface. The Swing tutorial on How to Use Tables shows you the basics of how to do this.
Or you can use the Bean Table Model which does all the work for you.
You have to override the getValueAt(...)
method:
@Override
public Object getValueAt(int row, int column) {
DataHolder data = dataVector_.get(row);
switch(column) {
case 0: return data.month;
case 1: return data.day;
case 2: return data.year;
default: return null;
}
Do you want to change this in the Table Model or the Table View? If you are using a JTable for the view, might I suggest working with the TableColumnModel which is accessible via the JTable.
精彩评论