create TableModel and populate jTable dynamically

前端 未结 3 1757
遥遥无期
遥遥无期 2021-01-12 10:54

I want to store the results of reading lucene index into jTable, so that I can make it sortable by different columns. From index I am reading terms with different measures o

3条回答
  •  旧巷少年郎
    2021-01-12 11: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 list;
    
        private MyModel() {
            list = new LinkedList();
        }
    
        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;
        }
    
    }
    

提交回复
热议问题