Search code examples
javaswingjtableabstracttablemodel

Not able to use a method declared in a class extending AbstractTableModel in JTable UI programming


I am getting the message "method is never used locally" after I've implemented the removeRow method. I am also unable to use/access this method.

class TableModel extends AbstractTableModel {

    private String[] columnNames = {"ID", "Name"};

         ArrayList<Entry> list;

         public TableModel(Entry[] entries) {
              // assigns entries to list
         }

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

         public String getColumnName(int col)
         {
             return columnNames[col];
         }

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

             // this method gives a "never used locally" message
         public void removeRow(int row)
         {
             list.remove(row);
             fireTableRowsDeleted(row, row);
         }

         public Object getValueAt(int row, int col) {
              Entry entry = list.get(row);
              if(entry != null)
              {
                  switch (col) {
                  case 0:
                       return entry.getId();
                  case 1:
                       return entry.getName();
                  default:
                       return "";
                  }
              }
         }
     }

I then try to access the removeRow(int row) by the following way when the delete button is pressed:

public void actionPerformed(ActionEvent event)
{
          int i =1;
      table.getModel().removeRow(i); // removeRow not recognised
}

Solution

  • You should cast to your class. When you do table.getModel you obtain an AbstractTableModel, which does not contain a method called removeRow

    try

    ((TableModel)table.getModel()).removeRow(i)