Trying to delete a row from JTable using Abstract Table Model

Mike_Toth
Mike_Toth used Ask the Experts™
on
Hi Guys,

 I am trying to delete a row of data on a JTable.  What I am trying to accomplish is to highlight the row by a mouseclick,
 then from the menu bar I am having the user select a "delete row" option.  I am working with an abstract
 Table Model with a deleteRow method.  I know I am doing something wrong in this method but I'm not sure what... it is not deleting nor dynamically reflecting the deleted row of data on the JTable gui:  
 
 P.S.  I am using a Vector of Vectors to store the data


Sorry if this looks a bit scattered, I had to cut/paste from a Linux NotePad type program
 
 Here are snippets of my main class  and Abstract Table Model :
 
 Main Class
 Table definition and mouse listener:
 
 usermodel = new DataFileTableModel("UserCtl.dat") ;
        userTable = new JTable();
        userTable.setModel(usermodel);
        userTable.createDefaultColumnsFromModel();
     
        userTable.addMouseListener(new MouseAdapter() {
             public void mouseClicked(MouseEvent evt) {
                  upoint = evt.getPoint();
                  rowToBeDeleted = userTable.rowAtPoint(upoint);
       
          }      
});


Menu Selection which calls the deleteRow Method in the model:
 
   deleteitem = new JMenuItem("Delete Row",'D');
       editmenu.add(deleteitem) ;
       deleteitem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               int delresp = JOptionPane.showConfirmDialog(null,"Are you sure you wish to delete this row ?",null, JOptionPane.YES_NO_OPTION) ;
               switch(delresp)   {
                  case JOptionPane.NO_OPTION:
                       return;
                  case JOptionPane.YES_OPTION:
                        switch (tabnum)
                           {
                            case 0:
                               usermodel.deleteRow(rowToBeDeleted);
                               break ;
                               .
                               .
                               .
                               
                          }
           
             }
        }
        });
       
       
Here is my Abstract Table Model... the deleteRow method is at the bottom:
 
 import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;




public class DataFileTableModel extends AbstractTableModel {
protected Vector data;
protected Vector columnNames ;
protected String datafile;

public DataFileTableModel(String f){
datafile = f;
initVectors();
}

public void initVectors() {
String aLine ;
data = new Vector();
columnNames = new Vector();
try {
FileInputStream fin = new FileInputStream(datafile);
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
// extract column names
StringTokenizer st1 =
new StringTokenizer(br.readLine(), "|");
while(st1.hasMoreTokens())
columnNames.addElement(st1.nextToken());
// extract data
while ((aLine = br.readLine()) != null) {
StringTokenizer st2 =
new StringTokenizer(aLine, "|");
while(st2.hasMoreTokens())
data.addElement(st2.nextToken());
}
br.close();
}
catch (Exception e) {
e.printStackTrace();
}
}

public int getRowCount() {
return data.size() / getColumnCount();
}

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

public String getColumnName(int columnIndex) {
String colName = "";

if (columnIndex <= getColumnCount())
colName = (String)columnNames.elementAt(columnIndex);

return colName;
}

public Class getColumnClass(int columnIndex){
return String.class;
}

public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}

public Object getValueAt(int rowIndex, int columnIndex) {
return (String)data.elementAt( (rowIndex * getColumnCount()) + columnIndex);
}



public void setValueAt(Object aValue, int rowIndex, int columnIndex) {

    data.setElementAt(aValue, (rowIndex * getColumnCount())+columnIndex) ;

    fireTableCellUpdated(rowIndex, columnIndex);


}
public void addRow(Object[] aRow) {
      for (int i=0; i < aRow.length; i++)
         data.add(aRow[i]);
      int size = getRowCount();
   
      fireTableRowsInserted(size-1,size-1);
     
   
        }
 
public void deleteRow(int rowNo)
       {
             if (rowNo < 0 || rowNo >= getRowCount())
                   return;
                
      int colCount = getColumnCount();
      int index = colCount * rowNo;
      System.out.println("in deleteRow  Row = " + rowNo);
      System.out.println("colCount = " + colCount);
      System.out.println("index       = " + index) ;
      
      for (int d = index; d <= colCount; d++)
           data.remove(d) ;
           fireTableRowsDeleted(rowNo,rowNo) ;
      

       }
       
 }
 
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
try with fireTableDataChanged() method. Why don't you use vector of vectors or vector of objects, where this objects encapsulate the columns of a row? Is much easier to mantain and much more readable code too.

Author

Commented:
Could you please give me an example ???
Ovi

Commented:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;

public class SimpleTable extends JFrame {
  private SmartTable table;
  private Actions actions;

  public SimpleTable() { init(); }

  private void init() {
    getContentPane().setLayout(new BorderLayout());
    setSize(600, 300);
    setLocation(300, 100);
    table = new SmartTable();
    actions = new Actions();
    getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    getContentPane().add(actions, BorderLayout.SOUTH);
    setVisible(true);
  }

  class Actions extends JPanel {
    JButton add = new JButton("Add");
    JButton remove = new JButton("Remove");
    JButton selected = new JButton("Dump selected");
    JButton dump = new JButton("Dump content to console");
    public Actions() {
      setLayout(new FlowLayout());
      setListeners();
      add(add);
      add(remove);
      add(selected);
      add(dump);
    }

    public DBObject createDBObject() {
      DBObject dbo = new DBObject();
      int curent = SimpleTable.this.table.getRowCount();
      dbo.f1 = "DBO " + curent + " field 1";dbo.f2 = "DBO " + curent + " field 2";
      dbo.f3 = "DBO " + curent + " field 3";dbo.f4 = "DBO " + curent + " field 4";
      dbo.f5 = "DBO " + curent + " field 5";dbo.f6 = "DBO " + curent + " field 6";
      dbo.f7 = "DBO " + curent + " field 7";dbo.f8 = "DBO " + curent + " field 8";
      return(dbo);
    }

    protected void setListeners() {
      add.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          SimpleTable.this.table.addDBObject(createDBObject());
        }
      });
      remove.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          try {
            int selected = SimpleTable.this.table.getSelectedRow();
            SimpleTable.this.table.removeDBObjectAt(selected);
            SimpleTable.this.table.setSelectedRow(selected);
          } catch(Exception e) {}
        }
      });
      selected.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          try {
            int row = SimpleTable.this.table.getSelectedRow();
            int col = SimpleTable.this.table.getSelectedColumn();
            System.out.println("Selected : [" + row + ", " + col + "]");
          } catch(Exception e) {}
        }
      });
      dump.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          Vector objs = SimpleTable.this.table.getDBObjects();
          for(int i = 0; i < objs.size(); i++) {
            DBObject o = (DBObject)objs.elementAt(i);
            System.out.println("DBObject " + i + ": " + o.f1 + ", " + o.f2 + ", " + o.f3 +
            ", " + o.f4 + ", " + o.f5 + ", " + o.f6 + ", " + o.f7 + ", " + o.f8);
          }
        }
      });
    }
  }

  class SmartTable extends JTable {
    SmartTableModel model;

    public SmartTable() {
      model = new SmartTableModel();
      createColumns();
      setModel(model);
      setForeground(Color.red);
      setBackground(new Color(255, 239, 185));
      setGridColor(Color.orange);
      setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    protected void createColumns() {
      for(int i = 0; i<model.getColumnCount(); i++) {
        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setHorizontalAlignment(model.cols[i].alignment);
        TableColumn column = new TableColumn(i, model.cols[i].width, renderer, null);
        addColumn(column);
      }
    }

    public void addDBObject(DBObject object) { model.addDBObject(object);}
    public void addDBObjects(Vector objects) { model.addData(objects);}
    public void removeDBObjectAt(int idx) { model.removeDBObjectAt(idx);}
    public DBObject getDBObject(int row) { return(model.getDBObject(row)); }
    public Vector getDBObjects() { return(model.getDBObjects()); }

    protected void setSelectedRow(int row) {
      if(row < 0)
        clearSelection();
      else {
        clearSelection();
        setRowSelectionInterval(row, row);
      }
    }

    protected void setSelectedCol(int col) {
      if(col < 0)
        clearSelection();
      else {
        clearSelection();
        setColumnSelectionInterval(col, col);
      }
    }
  }

  class SmartTableModel extends AbstractTableModel {
    protected ColumnDescriptor cols[] =  {
      new ColumnDescriptor("Field1", 40, JLabel.LEFT),
      new ColumnDescriptor("Field2", 50, JLabel.LEFT),
      new ColumnDescriptor("Field3", 100, JLabel.LEFT),
      new ColumnDescriptor("Field4", 60, JLabel.LEFT),
      new ColumnDescriptor("Field5", 50, JLabel.LEFT),
      new ColumnDescriptor("Field6", 40, JLabel.LEFT),
      new ColumnDescriptor("Field7", 40, JLabel.LEFT),
      new ColumnDescriptor("Field8", 40, JLabel.LEFT),
    };
    protected Vector dbObjects;

    public SmartTableModel() {
      dbObjects = new Vector();
    }

    public void addData(Vector v) {
      dbObjects.removeAllElements();
      for(int i = 0; i<v.size(); i++) {
        dbObjects.addElement((DBObject) v.elementAt(i));
      }
      updateObjects();
    }

    public void addDBObject(DBObject dbo) {
      dbObjects.addElement(dbo);
      updateObjects();
    }
    public void removeDBObjectAt(int idx) {
      dbObjects.removeElementAt(idx);
      updateObjects();
    }

    public DBObject getDBObject(int row) {
      return((DBObject)dbObjects.elementAt(row));
    }

    public Vector getDBObjects() {
      return(dbObjects);
    }

    protected void updateObjects() {
      fireTableDataChanged();
    }

    public int getColumnCount() { return(cols.length); }
    public int getRowCount() { return(dbObjects.size()); }
    public String getColumnName(int c) { return(cols[c].name); }
    public boolean isCellEditable(int row, int col) { return(true); }

    public Object getValueAt(int row, int col) {
      if(getRowCount() <= 0)
        return "";
      if(row<0||row>=getRowCount())
        return "";
      DBObject dbo = (DBObject) dbObjects.elementAt(row);
      switch(col) {
        case 0: return dbo.f1;
        case 1: return dbo.f2;
        case 2: return dbo.f3;
        case 3: return dbo.f4;
        case 4: return dbo.f5;
        case 5: return dbo.f6;
        case 6: return dbo.f7;
        case 7: return dbo.f8;
      }
      return "";
    }

  }

  class ColumnDescriptor {
    public String name;
    public int width;
    public int alignment;

    public ColumnDescriptor(String n, int w, int a) {
      name = n;
      width = w;
      alignment = a;
    }
  }

  class DBObject {
    public String f1;
    public String f2;
    public String f3;
    public String f4;
    public String f5;
    public String f6;
    public String f7;
    public String f8;
  }

  public static void main(String[] args) {
    SimpleTable t = new SimpleTable();
  }

}

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial