faqts : Computers : Programming : Languages : Java

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 9 people (22%) answered Yes
Recently 2 of 9 people (22%) answered Yes

Entry

How does one write a TableModelListener?

Oct 6th, 2002 06:38
Peter Simard,


I found this to work :

A: make sure you import javax.swing.table.TableModel;
B: extend class AbstractTableModel

class CustomTableModel extends AbstractTableModel
{
private String[] s;     //column names array
private Object[][] obj; //table data array

// These methods always need to be implemented.

public int getColumnCount() { return s.length; }
public int getRowCount() { return obj.length;}
public Object getValueAt(int row, int col) {return obj[row][col];}

// The default implementations of these methods in
// AbstractTableModel would work, but we can refine them.

public String getColumnName(int column) {return s[column];}
public Class getColumnClass(int c) {return getValueAt(0, c).getClass);}
public boolean isCellEditable(int row, int col) {return true;}
public void setColumnNamesArray(String[] strArray){ this.s = strArray;}
public void setTableItemsArray(Object[][] objectArray)
  { 
    this.obj = objectArray;
  }

public void setValueAt(Object aValue, int row, int column) 
{
//change the data in the cell to the new value and 
//alert all listeners by calling thier tableChanged() method

fireTableCellUpdated(row, column);
}


C: override method tableChanged:
//example:
public void tableChanged(TableModelEvent e)
{
JOptionPane.showMessageDialog(null,"Table data has changed at cell 
location\n---ROW: " + e.getFirstRow() + "\n---COL:" + e.getColumn());
}


D: define a table model for the data and add a TableModelListener

CustomTableModel ingredientModel = new CustomTableModel();
		ingredientModel.setColumnNamesArray(ingColNames);
		ingredientModel.setTableItemsArray(getIngredients());
                ingredientModel.addTableModelListener(this);