We help IT Professionals succeed at work.

how to delete rows in the "view" of JTable?

alen_ycc
alen_ycc asked
on
according MVC(Model-View-Controller) design, i think there should have a method to deal with the row deletion of the JTable's view, but not delete in JTable's Model...
Comment
Watch Question

Ovi

Commented:
According with the MVC pattern, the view is responsable only and only for rendering the data from the model. The model store all the data and the processing issues of it. So a corect MVC implementation will delete the data from the model which will notify the view about state changed.

Keep in mind that you have (according to MVC pattern) one single model and virtualy a infinity of views associated to that model.

Author

Commented:
ok, then how exactly can delete the rows in runtime?
If you delete a row in a Table but not in the underlying model then you are NOT deleting the row but "hiding" it in in that particular view. That function would therefore be the resposibility of the view, not the model.

The easiest way to do this is to build some row filtering class that sits between the view (JTable) and the model (DefaultTableModel). It adds itself to the TableModel as a listener and allows the JTable to add itself to it as a listener. It then proxies the conversation between the two.

You should be able to find a way of masking off or not displaying certain rows in the Table.
Ovi

Commented:
"If you delete a row in a Table but not in the underlying model then you are NOT deleting the row but
                     "hiding" it in in that particular view. That function would therefore be the resposibility of the view,
                     not the model." - The VIEW according to MVC pattern, is responsable for displaying the data from the MODEL, and only for this. Also, the VIE is in direct relation with the CONTROLLER, which listen for any kind of input events. So "hiding" data on the view is a result of implementing a hiding algorithm into the MODEL. This is not a sollution to avoid delete of data contained by the table unless the programmer want's this kind of behaviour.

alen_ycc : I will write shortly to you a example of doing that.
Ovi

Commented:
"If you delete a row in a Table but not in the underlying model then you are NOT deleting the row but                 "hiding" it in in that particular view. That function would therefore be the resposibility of the view,                           not the model." - The VIEW according to MVC pattern, is responsable for displaying the data from the MODEL, and only for this. Also, the VIEW is in direct relation with the CONTROLLER, which listen for any kind of input events. So "hidding" data on the view is a result of implementing a hidding algorithm into the MODEL. This is not a sollution to avoid delete of data contained by the table unless the programmer want's this kind of behaviour.

alen_ycc : I will write shortly to you a example of doing that.
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 dump = new JButton("Dump content to console");
    public Actions() {
      setLayout(new FlowLayout());
      setListeners();
      add(add);
      add(remove);
      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) {}
        }
      });
      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();
  }

}

Author

Commented:
Thanks Ovi, your code is excellent, thanks!
may i have your ICQ No.? my no. is 81119581,

best regards,
alen_ycc

Explore More ContentExplore courses, solutions, and other research materials related to this topic.