1 package org.objectstyle.cayenne.swing; 2 3 import java.awt.Component ; 4 import java.util.ArrayList ; 5 import java.util.Arrays ; 6 import java.util.Collection ; 7 import java.util.List ; 8 import java.util.Map ; 9 10 import javax.swing.JTable ; 11 import javax.swing.table.AbstractTableModel ; 12 13 import org.apache.commons.collections.map.SingletonMap; 14 15 20 public class TableBinding extends BindingBase { 21 22 25 public static final String ITEM_VAR = "item"; 26 27 protected JTable table; 28 protected String [] headers; 29 protected BindingExpression[] columns; 30 protected boolean[] editableState; 31 protected Class [] columnClass; 32 protected List list; 33 34 public TableBinding(JTable table, String listBinding, String [] headers, 35 BindingExpression[] columns, Class [] columnClass, boolean[] editableState) { 36 37 super(listBinding); 38 this.table = table; 39 this.headers = headers; 40 this.columns = columns; 41 this.editableState = editableState; 42 this.columnClass = columnClass; 43 44 table.setModel(new BoundTableModel()); 45 } 46 47 public void setContext(Object object) { 48 super.setContext(object); 49 50 this.list = updateList(); 51 } 52 53 public Component getView() { 54 return table; 55 } 56 57 public void updateView() { 58 this.list = updateList(); 59 ((BoundTableModel) table.getModel()).fireTableDataChanged(); 60 } 61 62 int getListSize() { 63 return (list != null) ? list.size() : 0; 64 } 65 66 List updateList() { 67 if (getContext() == null) { 68 return null; 69 } 70 71 Object list = getValue(); 72 if (list == null) { 73 return null; 74 } 75 76 if (list instanceof List ) { 77 return (List ) list; 78 } 79 80 if (list instanceof Object []) { 81 Object [] objects = (Object []) list; 82 return Arrays.asList(objects); 83 } 84 85 if (list instanceof Collection ) { 86 return new ArrayList ((Collection ) list); 87 } 88 89 throw new BindingException("List expected, got - " + list); 90 } 91 92 final class BoundTableModel extends AbstractTableModel { 93 94 Map listContext = new SingletonMap(ITEM_VAR, null); 97 98 public int getColumnCount() { 99 return headers.length; 100 } 101 102 public int getRowCount() { 103 return getListSize(); 104 } 105 106 public boolean isCellEditable(int rowIndex, int columnIndex) { 107 return editableState[columnIndex]; 108 } 109 110 public Object getValueAt(int rowIndex, int columnIndex) { 111 Object item = list.get(rowIndex); 112 listContext.put(ITEM_VAR, item); 113 return columns[columnIndex].getValue(getContext(), listContext); 114 } 115 116 public String getColumnName(int column) { 117 return headers[column]; 118 } 119 120 public Class getColumnClass(int columnIndex) { 121 return columnClass[columnIndex]; 122 } 123 124 public void setValueAt(Object value, int rowIndex, int columnIndex) { 125 Object item = list.get(rowIndex); 126 listContext.put(ITEM_VAR, item); 127 columns[columnIndex].setValue(getContext(), listContext, value); 128 } 129 } 130 } | Popular Tags |