1 7 8 package org.jdesktop.swing.data; 9 10 import javax.swing.event.TableModelEvent ; 11 import javax.swing.event.TableModelListener ; 12 13 21 public class TableModelExtAdapter extends AbstractDataModel { 22 23 private DefaultTableModelExt model; 24 private int rowIndex = -1; 25 private boolean updatingModel = false; 26 27 public TableModelExtAdapter(DefaultTableModelExt model) { 28 this.model = model; 29 model.addTableModelListener(new TableModelListener () { 30 public void tableChanged(TableModelEvent e) { 31 if (updatingModel) { 32 return; 33 } 34 if (e.getType() == TableModelEvent.UPDATE) { 35 if (rowIndex >= e.getFirstRow() && rowIndex <= e.getLastRow()) { 36 int columnIndex = e.getColumn(); 37 final DefaultTableModelExt model = TableModelExtAdapter.this.model; 38 fireColumnsChanged(model, columnIndex, columnIndex); 40 } 41 } 42 } 43 private void fireColumnsChanged(DefaultTableModelExt model, int firstColumn, int lastColumn) { 44 if (firstColumn < 0) { 45 firstColumn = 0; 46 lastColumn = model.getColumnCount()-1; 47 } 48 for (int col = firstColumn; col <= lastColumn; col++) { 49 fireValueChanged(model.getColumnMetaData(col).getName()); 50 } 51 52 } 53 }); 54 } 55 56 public String [] getFieldNames() { 57 int columnCount = model.getColumnCount(); 58 String columnNames[] = new String [columnCount]; 59 MetaData metaData[] = model.getMetaData(); 60 for(int i = 0; i < columnCount; i++) { 61 columnNames[i] = metaData[i].getName(); 62 } 63 return columnNames; 64 } 65 66 public MetaData getMetaData(String fieldName) { 67 return model.getColumnMetaData(model.getColumnIndex(fieldName)); 68 } 69 70 public int getFieldCount() { 71 return model.getColumnCount(); 72 } 73 74 public Object getValue(String fieldName) { 75 return getRecordIndex() >= 0 ? 76 model.getValueAt(getRecordIndex(), model.getColumnIndex(fieldName)) : null; 77 } 78 79 protected void setValueImpl(String fieldName, Object value) { 80 if (getRecordIndex() < 0) return; 81 updatingModel = true; 82 model.setValueAt(value, getRecordIndex(), model.getColumnIndex(fieldName)); 83 updatingModel = false; 84 } 85 86 93 public void setRecordIndex(int rowIndex) { 94 if (rowIndex >= model.getRowCount()) { 95 throw new IndexOutOfBoundsException ("row index " + rowIndex + 96 "exceeds row count " + 97 model.getRowCount()); 98 } 99 if (this.rowIndex != rowIndex) { 100 this.rowIndex = rowIndex; 101 String fieldNames[] = getFieldNames(); 102 for(int i = 0; i < fieldNames.length; i++) { 103 fireValueChanged(fieldNames[i]); 104 } 105 } 106 } 107 108 112 public int getRecordIndex() { 113 return rowIndex; 114 } 115 116 121 public int getRecordCount() { 122 return model.getRowCount(); 123 } 124 } 125 | Popular Tags |