Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subclass DefaultTableModel and change its dataVector

Tags:

java

swing

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 insertRow(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.

like image 649
doku Avatar asked Sep 19 '25 10:09

doku


2 Answers

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.

like image 142
camickr Avatar answered Sep 21 '25 23:09

camickr


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;
    }
like image 44
multiholle Avatar answered Sep 22 '25 01:09

multiholle