create TableModel and populate jTable dynamically

为君一笑 提交于 2019-12-01 04:05:45

When you are inserting, deleting or updating data in your model, you need to notify the GUI of the changes. You can do this with the fire-methods in the AbstractTableModel.

I.e. if you add an element to your list, you also have to call fireTableRowsInserted(int firstRow, int lastRow) so that the visible layer can be updated.

Have a look at addElement(MyElement e) in the code below:

public class MyModel extends AbstractTableModel {

    private static final String[] columnNames = {"column 1", "column 2"};
    private final LinkedList<MyElement> list;

    private MyModel() {
        list = new LinkedList<MyElement>();
    }

    public void addElement(MyElement e) {
        // Adds the element in the last position in the list
        list.add(e);
        fireTableRowsInserted(list.size()-1, list.size()-1);
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public int getRowCount() {
        return list.size();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        switch(columnIndex) {
            case 0: return list.get(rowIndex).getColumnOne();
            case 1: return list.get(rowIndex).getColumnOne();
        }
        return null;
    }

}

There is no need to create a custom TableModel for this. Just use the DefaultListModel.

The DefaultListModel allows you to dynamcially add rows to the model using the addRow(...) method and it automatically invokes the appropriate fireXXX method to tell the table to repaint itself.

The basic code would be:

DefaultTableModel model = new DefaultTableModel( columnNames );

while (...)
{
  Vector row = new Vector();
  row.add(...)
  row.add(...)
  model.addRow( row );
}

JTable table = new JTable( model );

You don't need to create a custom TableModel everytime. Sometimes you can start with the DefaultTableModel.

You dont have to create an Object[][]. Just make your redoviLista a list of lists:

redoviLista.add( new ArrayList<Object>(termText, df, idf, tfidf) ); #pseudocode

then you implement getValueAt like this:

getValueAt(int row, int column){
  redoviLista.get(row).get(column);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!