KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > form > editors2 > TableModelEditor


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.form.editors2;
21
22 import java.awt.*;
23 import java.beans.*;
24 import java.util.*;
25 import java.io.*;
26 import javax.swing.table.*;
27
28 import org.openide.util.NbBundle;
29 import org.openide.explorer.propertysheet.editors.XMLPropertyEditor;
30 import org.netbeans.modules.form.NamedPropertyEditor;
31
32 /**
33 * A property editor for jjavax.swing.table.TableModel.
34 * @author Ian Formanek, Tomas Pavek
35 */

36
37 public class TableModelEditor implements PropertyEditor, XMLPropertyEditor, NamedPropertyEditor {
38
39     public TableModelEditor() {
40         support = new PropertyChangeSupport (this);
41     }
42
43     public Object JavaDoc getValue () {
44         return table;
45     }
46
47     public void setValue (Object JavaDoc value) {
48         table = new NbTableModel ((TableModel) value);
49         support.firePropertyChange ("", null, null); // NOI18N
50
}
51
52     public String JavaDoc getAsText () {
53         return null;
54     }
55
56     public void setAsText (String JavaDoc string) {
57     }
58
59     public String JavaDoc getJavaInitializationString () {
60         TableModel m = (TableModel) getValue ();
61         StringBuffer JavaDoc titlesSB = new StringBuffer JavaDoc ();
62         int i = m.getColumnCount ();
63         int j = m.getRowCount ();
64         titlesSB.append ("{\n\t\t"); // NOI18N
65
if (i > 0) {
66             String JavaDoc s = m.getColumnName (0);
67             titlesSB.append ("\"").append (s != null ? s : "").append ('"'); // NOI18N
68
for (int k = 1; k < i; k++) {
69                 String JavaDoc s1 = m.getColumnName (k);
70                 titlesSB.append (", \"").append (s1 != null ? s1 : "").append ('"'); // NOI18N
71
}
72         }
73         titlesSB.append ("\n\t}"); // NOI18N
74

75         boolean generateTypes = false;
76         StringBuffer JavaDoc typesSB = new StringBuffer JavaDoc ();
77         typesSB.append ("{\n\t\t"); // NOI18N
78
if (i > 0) {
79             typesSB.append (m.getColumnClass (0).getName ()).append (".class"); // NOI18N
80
if (m.getColumnClass (0) != Object JavaDoc.class)
81                 generateTypes = true;
82             for (int k = 1; k < i; k++) {
83                 if (m.getColumnClass (k) != Object JavaDoc.class)
84                     generateTypes = true;
85                 typesSB.append (", ").append (m.getColumnClass (k).getName ()).append (".class"); // NOI18N
86
}
87         }
88         typesSB.append ("\n\t}"); // NOI18N
89

90         boolean generateEditable = false;
91         StringBuffer JavaDoc editableSB = new StringBuffer JavaDoc ();
92         editableSB.append ("{\n\t\t"); // NOI18N
93
if (i > 0) {
94             editableSB.append (m.isCellEditable (0, 0));
95             if (!m.isCellEditable (0, 0)) generateEditable = true;
96             for (int k = 1; k < i; k++) {
97                 if (!m.isCellEditable (0, k)) generateEditable = true;
98                 editableSB.append (", ").append (m.isCellEditable (0, k)); // NOI18N
99
}
100         }
101         editableSB.append ("\n\t}"); // NOI18N
102

103         StringBuffer JavaDoc dataSB = new StringBuffer JavaDoc ();
104         dataSB.append ("{\n\t\t"); // NOI18N
105
if (j > 0) {
106             for (int l = 0; l < j; l++) {
107                 if (l != 0)
108                     dataSB.append (",\n\t\t"); // NOI18N
109
if (i == 0) {
110                     dataSB.append ("{}"); // NOI18N
111
} else {
112                     Object JavaDoc obj = m.getValueAt (l, 0);
113                     dataSB.append ('{').append (getAsString (obj));
114                     for (int i1 = 1; i1 < i; i1++) {
115                         obj = m.getValueAt (l, i1);
116                         dataSB.append (", ").append (getAsString (obj)); // NOI18N
117
}
118                     dataSB.append ('}');
119                 }
120             }
121         }
122         dataSB.append ("\n\t}"); // NOI18N
123
if (generateEditable || generateTypes) {
124             return
125                 "new javax.swing.table.DefaultTableModel(\n" + // NOI18N
126
"\tnew Object [][] " + dataSB.toString() + ",\n" + // NOI18N
127
"\tnew String [] " + titlesSB.toString() + "\n" + // NOI18N
128
") {\n" + // NOI18N
129
(generateTypes ? (
130                      "\tClass[] types = new Class [] " + typesSB.toString() + ";\n") : // NOI18N
131
"") + // NOI18N
132
(generateEditable ? (
133                      "\tboolean[] canEdit = new boolean [] " + editableSB.toString() + ";\n") : // NOI18N
134
"") + // NOI18N
135
(generateTypes ? (
136                      "\n" + // NOI18N
137
"\tpublic Class getColumnClass(int columnIndex) {\n" + // NOI18N
138
"\t\treturn types [columnIndex];\n" + // NOI18N
139
"\t}\n") : // NOI18N
140
"") + // NOI18N
141
(generateEditable ? (
142                      "\n" + // NOI18N
143
"\tpublic boolean isCellEditable(int rowIndex, int columnIndex) {\n" + // NOI18N
144
"\t\treturn canEdit [columnIndex];\n" + // NOI18N
145
"\t}\n") : // NOI18N
146
"") + // NOI18N
147
"}"; // NOI18N
148
} else {
149             return
150                 "new javax.swing.table.DefaultTableModel(\n" + // NOI18N
151
"\tnew Object [][] " + dataSB.toString() + ",\n" + // NOI18N
152
"\tnew String [] " + titlesSB.toString() + "\n" + // NOI18N
153
")"; // NOI18N
154
}
155     }
156
157     public String JavaDoc[] getTags () {
158         return null;
159     }
160
161     public boolean isPaintable () {
162         return false;
163     }
164
165     public void paintValue (Graphics g, Rectangle rectangle) {
166     }
167
168     public boolean supportsCustomEditor () {
169         return true;
170     }
171
172     public Component getCustomEditor () {
173         return new CustomTableModelEditor (this);
174     }
175
176     public void addPropertyChangeListener (PropertyChangeListener propertyChangeListener) {
177         support.addPropertyChangeListener (propertyChangeListener);
178     }
179
180     public void removePropertyChangeListener (PropertyChangeListener propertyChangeListener) {
181         support.removePropertyChangeListener (propertyChangeListener);
182     }
183
184     // ------------
185
// XMLPropertyEditor implementation
186

187     private static final String JavaDoc XML_TABLE = "Table"; // NOI18N
188
private static final String JavaDoc XML_COLUMN = "Column"; // NOI18N
189
private static final String JavaDoc XML_DATA = "Data"; // NOI18N
190

191     private static final String JavaDoc ATTR_COLUMN_COUNT = "columnCount"; // NOI18N
192
private static final String JavaDoc ATTR_ROW_COUNT = "rowCount"; // NOI18N
193
private static final String JavaDoc ATTR_TITLE = "title"; // NOI18N
194
private static final String JavaDoc ATTR_TYPE = "type"; // NOI18N
195
private static final String JavaDoc ATTR_EDITABLE = "editable"; // NOI18N
196
private static final String JavaDoc ATTR_VALUE = "value"; // NOI18N
197

198     public org.w3c.dom.Node JavaDoc storeToXML(org.w3c.dom.Document JavaDoc doc) {
199         org.w3c.dom.Element JavaDoc tableEl = doc.createElement(XML_TABLE);
200
201         int colCount = table.getColumnCount();
202         int rowCount = table.getRowCount();
203
204         tableEl.setAttribute(ATTR_COLUMN_COUNT, Integer.toString(colCount));
205         tableEl.setAttribute(ATTR_ROW_COUNT, Integer.toString(rowCount));
206
207         for (int i=0; i < colCount; i++) {
208             NbTableModel.ColumnItem column = table.getColumnItem(i);
209             org.w3c.dom.Element JavaDoc columnEl = doc.createElement(XML_COLUMN);
210             columnEl.setAttribute(ATTR_TITLE, column.title);
211             columnEl.setAttribute(ATTR_TYPE, column.type.getName());
212             columnEl.setAttribute(ATTR_EDITABLE, column.editable ? "true":"false"); // NOI18N
213

214             boolean anyData = false;
215             for (int j=0; j < rowCount; j++)
216                 if (column.rows.get(j) != null) {
217                     anyData = true;
218                     break;
219                 }
220
221             if (anyData)
222                 for (int j=0; j < rowCount; j++) {
223                     org.w3c.dom.Element JavaDoc dataEl = doc.createElement(XML_DATA);
224                     dataEl.setAttribute(ATTR_VALUE, valueToString(column.rows.get(j)));
225                     columnEl.appendChild(dataEl);
226                 }
227
228             tableEl.appendChild(columnEl);
229         }
230
231         return tableEl;
232     }
233
234     public void readFromXML(org.w3c.dom.Node JavaDoc element) throws IOException {
235         if (!XML_TABLE.equals(element.getNodeName()))
236             throw new IOException(getReadingErrorMessage()); // NOI18N
237

238         org.w3c.dom.NamedNodeMap JavaDoc tableAttr = element.getAttributes();
239         if (tableAttr == null)
240             return;
241
242         IOException ioex = null;
243         org.w3c.dom.Node JavaDoc node;
244
245         // first read columnCount and rowCount attributes
246
int columnCount = -1;
247         int rowCount = -1;
248
249         node = tableAttr.getNamedItem(ATTR_COLUMN_COUNT);
250         if (node != null) {
251             try {
252                 columnCount = Integer.parseInt(node.getNodeValue());
253             }
254             catch (java.lang.NumberFormatException JavaDoc e) {
255                 ioex = new IOException(getReadingErrorMessage());
256                 org.openide.ErrorManager.getDefault().annotate(ioex, e);
257             }
258         }
259
260         node = tableAttr.getNamedItem(ATTR_ROW_COUNT);
261         if (node != null) {
262             try {
263                 rowCount = Integer.parseInt(node.getNodeValue());
264             }
265             catch (java.lang.NumberFormatException JavaDoc e) {
266                 if (ioex == null)
267                    ioex = new IOException(getReadingErrorMessage());
268                 org.openide.ErrorManager.getDefault().annotate(ioex, e);
269             }
270         }
271
272         if (columnCount < 0 || rowCount < 0) {
273             if (ioex == null)
274                ioex = new IOException(getReadingErrorMessage());
275             throw ioex;
276         }
277
278         java.util.List JavaDoc columns = new ArrayList(columnCount);
279
280         // go through the column data nodes and read the columns
281
org.w3c.dom.NodeList JavaDoc columnNodes = element.getChildNodes();
282         for (int i=0, cCount=columnNodes.getLength(); i < cCount; i++) {
283             org.w3c.dom.Node JavaDoc cNode = columnNodes.item(i);
284             if (!XML_COLUMN.equals(cNode.getNodeName()))
285                 continue;
286
287             org.w3c.dom.NamedNodeMap JavaDoc columnAttr = cNode.getAttributes();
288             if (columnAttr == null)
289                 continue;
290
291             // get title, type and editable attributes
292
String JavaDoc title = null;
293             Class JavaDoc type = null;
294             Boolean JavaDoc editable = null;
295
296             node = columnAttr.getNamedItem(ATTR_TITLE);
297             if (node != null)
298                 title = node.getNodeValue();
299
300             node = columnAttr.getNamedItem(ATTR_TYPE);
301             if (node != null) {
302                 try {
303                     type = Class.forName(node.getNodeValue());
304                 }
305                 catch (Exception JavaDoc e) {
306                     ioex = new IOException(getReadingErrorMessage());
307                     org.openide.ErrorManager.getDefault().annotate(ioex, e);
308                 }
309             }
310
311             node = columnAttr.getNamedItem(ATTR_EDITABLE);
312             if (node != null)
313                 editable = Boolean.valueOf(node.getNodeValue());
314
315             if (title == null || type == null || editable == null) {
316                 if (ioex == null)
317                    ioex = new IOException(getReadingErrorMessage());
318                 throw ioex;
319             }
320
321             java.util.List JavaDoc columnData = new ArrayList(rowCount);
322
323             // read the column data
324
org.w3c.dom.NodeList JavaDoc dataNodes = cNode.getChildNodes();
325             for (int j=0, dCount=dataNodes.getLength(); j < dCount; j++) {
326                 org.w3c.dom.Node JavaDoc dNode = dataNodes.item(j);
327                 if (!XML_DATA.equals(dNode.getNodeName()))
328                     continue;
329
330                 org.w3c.dom.NamedNodeMap JavaDoc dataAttr = dNode.getAttributes();
331                 if (dataAttr == null)
332                     continue;
333
334                 // get the value attribute
335
Object JavaDoc value = null;
336                 node = dataAttr.getNamedItem(ATTR_VALUE);
337                 if (node != null) {
338                     try {
339                         value = stringToValue(node.getNodeValue(), type);
340                     }
341                     catch (IllegalArgumentException JavaDoc e) {
342                         ioex = new IOException(getReadingErrorMessage());
343                         org.openide.ErrorManager.getDefault().annotate(ioex, e);
344                         throw ioex;
345                     }
346                 }
347
348                 columnData.add(value);
349             }
350
351             // check the row count
352
if (columnData.size() != rowCount) {
353                 if (columnData.size() == 0)
354                     for (int ii=0; ii < rowCount; ii++)
355                         columnData.add(null);
356                 else
357                     throw new IOException(getReadingErrorMessage());
358             }
359
360             // create the column
361
columns.add(new NbTableModel.ColumnItem(title,
362                                                     type,
363                                                     editable.booleanValue(),
364                                                     columnData));
365         }
366
367         // check the column count
368
if (columns.size() != columnCount)
369             throw new IOException(getReadingErrorMessage());
370
371         // create the model instance
372
table = new NbTableModel(columns, rowCount);
373     }
374
375     // -----------
376

377     private static ResourceBundle getBundle() {
378         return NbBundle.getBundle(TableModelEditor.class);
379     }
380
381     private static String JavaDoc getReadingErrorMessage() {
382         return getBundle().getString("ERR_InvalidXMLFormat"); // NOI18N
383
}
384
385     private static String JavaDoc valueToString(Object JavaDoc value) {
386         if (value instanceof Integer JavaDoc || value instanceof Short JavaDoc
387                 || value instanceof Byte JavaDoc || value instanceof Long JavaDoc
388                 || value instanceof Float JavaDoc || value instanceof Double JavaDoc
389                 || value instanceof Boolean JavaDoc || value instanceof Character JavaDoc)
390             return value.toString();
391
392         if (value instanceof String JavaDoc)
393             return (String JavaDoc)value;
394
395         if (value == null)
396             return "null"; // NOI18N
397

398         return null; // is not a primitive type
399
}
400
401     private static Object JavaDoc stringToValue(String JavaDoc encoded, Class JavaDoc type) {
402         if ("null".equals(encoded)) // NOI18N
403
return null;
404
405         if (type == Object JavaDoc.class)
406             return encoded;
407
408         if (Integer JavaDoc.class.isAssignableFrom(type) || Integer.TYPE.equals(type))
409             return Integer.valueOf(encoded);
410         if (Short JavaDoc.class.isAssignableFrom(type) || Short.TYPE.equals(type))
411             return Short.valueOf(encoded);
412         if (Byte JavaDoc.class.isAssignableFrom(type) || Byte.TYPE.equals(type))
413             return Byte.valueOf(encoded);
414         if (Long JavaDoc.class.isAssignableFrom(type) || Long.TYPE.equals(type))
415             return Long.valueOf(encoded);
416         if (Float JavaDoc.class.isAssignableFrom(type) || Float.TYPE.equals(type))
417             return Float.valueOf(encoded);
418         if (Double JavaDoc.class.isAssignableFrom(type) || Double.TYPE.equals(type))
419             return Double.valueOf(encoded);
420         if (Boolean JavaDoc.class.isAssignableFrom(type) || Boolean.TYPE.equals(type))
421             return Boolean.valueOf(encoded);
422         if (Character JavaDoc.class.isAssignableFrom(type) || Character.TYPE.equals(type))
423             return new Character JavaDoc(encoded.charAt(0));
424         if (String JavaDoc.class.isAssignableFrom(type))
425             return encoded;
426
427         throw new IllegalArgumentException JavaDoc();
428     }
429
430     static String JavaDoc getAsString (Object JavaDoc o) {
431         if (o == null) return "null"; // NOI18N
432

433         if (o instanceof String JavaDoc)
434             return "\"" + o + "\""; // NOI18N
435

436         String JavaDoc s = o.getClass ().getName ();
437         int g = s.lastIndexOf ('.');
438         if (g >= 0) s = s.substring (g + 1, s.length ());
439
440         String JavaDoc cast = ""; // NOI18N
441
if (o instanceof Byte JavaDoc)
442             cast = "(byte) "; // NOI18N
443
else if (o instanceof Short JavaDoc)
444             cast = "(short) "; // NOI18N
445

446         return "new " + s + "(" + cast + o + ")"; // NOI18N
447
}
448
449     static Object JavaDoc getDefaultValue (Class JavaDoc c) {
450         return null;
451     }
452     
453     // NamedPropertyEditor implementation
454
public String JavaDoc getDisplayName() {
455         return NbBundle.getBundle(getClass()).getString("CTL_TableModelEditor_DisplayName"); // NOI18N
456
}
457
458     // -----------------------------------------------------------------------------
459
// NbTableModel
460

461     public static class NbTableModel extends AbstractTableModel implements Externalizable {
462         /** generated Serialized Version UID */
463         static final long serialVersionUID = -6843008677521167210L;
464
465         java.util.List JavaDoc columns;
466         int rowCount;
467
468         transient boolean alwaysEditable = false;
469
470         /** For externalization only */
471         public NbTableModel() {
472         }
473
474         public NbTableModel(String JavaDoc[] titles, Class JavaDoc[] types, boolean[] editable) {
475             this(titles,types,editable,4);
476         }
477
478         public NbTableModel(String JavaDoc[] titles, Class JavaDoc[] types, boolean[] editable, int rowCount) {
479             this.rowCount = rowCount;
480             columns = new ArrayList(titles.length);
481             for (int i=0; i < titles.length; i++)
482                 columns.add(new ColumnItem(titles[i],types[i],editable[i],rowCount));
483         }
484
485         public NbTableModel(TableModel createFrom) {
486             ResourceBundle bundle = getBundle();
487             if (createFrom == null) {
488                 rowCount = 4; // 4 rows and 4 columns by default
489
columns = new ArrayList(20);
490                 for (int i=0; i < 4; i++)
491                     columns.add(new ColumnItem(bundle.getString("CTL_Title")+" "+Integer.toString(i+1),
492                                                Object JavaDoc.class, true, rowCount));
493             } else {
494                 rowCount = createFrom.getRowCount();
495                 int colCount = createFrom.getColumnCount();
496                 columns = new ArrayList(colCount);
497
498                 if (createFrom instanceof NbTableModel) {
499                     NbTableModel model = (NbTableModel) createFrom;
500
501                     for (int i=0; i < colCount; i++) {
502                         ColumnItem ci = (ColumnItem) model.columns.get(i);
503                         columns.add(new ColumnItem(ci));
504                     }
505                 } else {
506                     for (int i=0; i < colCount; i++) {
507                         ColumnItem ci = new ColumnItem(createFrom.getColumnName(i),
508                                                        createFrom.getColumnClass(i),
509                                                        true, rowCount);
510                         for (int j=0; j < rowCount; j++)
511                             ci.rows.set(j, createFrom.getValueAt(j,i));
512                         columns.add(ci);
513                     }
514                 }
515             }
516         }
517
518         NbTableModel(java.util.List JavaDoc columns, int rowCount) {
519             this.columns = columns;
520             this.rowCount = rowCount;
521         }
522
523         // from AbstractTableModel
524
public Class JavaDoc getColumnClass(int i) {
525             ColumnItem ci = (ColumnItem) columns.get(i);
526             return ci.type;
527         }
528
529         public void setColumnClass(int i, Class JavaDoc type) {
530             ColumnItem ci = (ColumnItem) columns.get(i);
531             ci.type = type;
532         }
533
534         // from AbstractTableModel
535
public String JavaDoc getColumnName(int i) {
536             ColumnItem ci = (ColumnItem) columns.get(i);
537             return ci.title;
538         }
539
540         public void setColumnName(int i, String JavaDoc title) {
541             ColumnItem ci = (ColumnItem) columns.get(i);
542             ci.title = title;
543         }
544
545         // from TableModel
546
public int getRowCount() {
547             return rowCount;
548         }
549
550         // from TableModel
551
public int getColumnCount() {
552             return columns.size();
553         }
554
555         public boolean isColumnEditable(int i) {
556             // this method returns design time settings - doesn't reflect alwaysEditable
557
ColumnItem ci = (ColumnItem) columns.get(i);
558             return ci.editable;
559         }
560
561         // from AbstractTableModel
562
public boolean isCellEditable(int i, int j) {
563             // this is used by a real table - alwaysEditable true means that table
564
// is fully editable (no matter the design settings)
565
if (alwaysEditable) return true;
566             ColumnItem ci = (ColumnItem) columns.get(j);
567             return ci.editable;
568         }
569
570         public void setColumnEditable(int i, boolean editable) {
571             ColumnItem ci = (ColumnItem) columns.get(i);
572             ci.editable = editable;
573         }
574
575         // from TableModel
576
public Object JavaDoc getValueAt(int row, int column) {
577             ColumnItem ci = (ColumnItem) columns.get(column);
578             return ci.rows.get(row);
579         }
580
581         // from AbstractTableModel
582
public void setValueAt(Object JavaDoc obj, int row, int column) {
583             ColumnItem ci = (ColumnItem) columns.get(column);
584             ci.rows.set(row, obj);
585             fireTableCellUpdated(row, column);
586         }
587
588         private ColumnItem getColumnItem(int i) {
589             return (ColumnItem) columns.get(i);
590         }
591
592         void setRowCount(int newRowCount) {
593             if (newRowCount == rowCount) return;
594
595             for (int i=0, n=columns.size(); i < n; i++) {
596                 java.util.List JavaDoc rows = ((ColumnItem)columns.get(i)).rows;
597                 if (newRowCount > rowCount) {
598                     for (int nr = newRowCount-rowCount; nr > 0; nr--)
599                         rows.add(null);
600                 }
601                 else { // newRowCount < rowCount
602
for (int rn = rowCount - newRowCount; rn > 0; rn--)
603                         rows.remove(newRowCount + rn - 1);
604                 }
605             }
606
607             int rc = rowCount;
608             rowCount = newRowCount;
609
610             if (newRowCount > rc)
611                 fireTableRowsInserted(rc, newRowCount - 1);
612             else // newRowCount < rc
613
fireTableRowsDeleted(newRowCount, rc - 1);
614         }
615
616         // adds one row at the index
617
void addRow(int index) {
618             if (index >= 0 && index <= rowCount) {
619                 for (int i=0, n=columns.size(); i < n; i++)
620                     ((ColumnItem)columns.get(i)).rows.add(index, null);
621
622                 rowCount++;
623                 fireTableRowsInserted(index, index);
624             }
625         }
626
627         // removes one row from index
628
void removeRow(int index) {
629             if (index >= 0 && index < rowCount) {
630                 for (int i=0, n=columns.size(); i < n; i++)
631                     ((ColumnItem)columns.get(i)).rows.remove(index);
632
633                 rowCount--;
634                 fireTableRowsDeleted(index, index);
635             }
636         }
637
638         void moveRow(int fromIndex, int toIndex) {
639             if (columns.size() > 0
640                     && fromIndex >= 0 && fromIndex < rowCount
641                     && toIndex >= 0 && toIndex < rowCount
642                     && fromIndex != toIndex) {
643
644                 for (int i=0, n=columns.size(); i < n; i++) {
645                     java.util.List JavaDoc rows = ((ColumnItem)columns.get(i)).rows;
646                     Object JavaDoc obj = rows.get(toIndex);
647                     rows.set(toIndex, rows.get(fromIndex));
648                     rows.set(fromIndex, obj);
649                 }
650                 fireTableStructureChanged();
651             }
652         }
653
654         void setColumnCount(int newColumnCount) {
655             ResourceBundle bundle = getBundle();
656             int colCount = columns.size();
657             if (newColumnCount == colCount) return;
658
659             if (newColumnCount > colCount) {
660                 for (int nc=newColumnCount-colCount; nc > 0; nc--)
661                     columns.add(new ColumnItem(bundle.getString("CTL_Title")+" "+Integer.toString(newColumnCount-nc+1),
662                                                Object JavaDoc.class, true, rowCount));
663             } else { // newColumnCount < colCount
664
for (int cn=colCount-newColumnCount; cn > 0; cn--)
665                     columns.remove(newColumnCount + cn - 1);
666             }
667             
668             fireTableStructureChanged();
669         }
670
671         // adds one column at index
672
void addColumn(int index) {
673             if (index >=0 && index <= columns.size()) {
674                 columns.add(index, new ColumnItem(getBundle().getString("CTL_Title")+" "+Integer.toString(index+1),
675                                                   Object JavaDoc.class, true, rowCount));
676                 // rename default titles
677
for (int i=index+1, n=columns.size(); i < n; i++) {
678                     ColumnItem ci = (ColumnItem) columns.get(i);
679                     renameDefaultColumnTitle(ci, i, i+1);
680                 }
681                 fireTableStructureChanged();
682             }
683         }
684
685         // removes one column at index
686
void removeColumn(int index) {
687             if (index >=0 && index < columns.size()) {
688                 columns.remove(index);
689
690                 // rename default titles
691
for (int i=index, n=columns.size(); i < n; i++) {
692                     ColumnItem ci = (ColumnItem) columns.get(i);
693                     renameDefaultColumnTitle(ci, i+2, i+1);
694                 }
695                 fireTableStructureChanged();
696             }
697         }
698
699         void moveColumn(int fromIndex,int toIndex) {
700             if (fromIndex >= 0 && fromIndex < columns.size()
701                     && toIndex >= 0 && toIndex < columns.size()
702                     && fromIndex != toIndex) {
703
704                 ColumnItem ciFrom = (ColumnItem) columns.get(fromIndex);
705                 ColumnItem ciTo = (ColumnItem) columns.get(toIndex);
706
707                 // also rename default titles
708
renameDefaultColumnTitle(ciFrom, fromIndex+1, toIndex+1);
709                 renameDefaultColumnTitle(ciTo, toIndex+1, fromIndex+1);
710
711                 columns.set(toIndex, ciFrom);
712                 columns.set(fromIndex, ciTo);
713                 fireTableStructureChanged();
714             }
715         }
716
717         // renames default column title according to new column's position
718
// e.g. with params 2 and 3 - "Title 2" is renamed to "Title 3"
719
private static void renameDefaultColumnTitle(ColumnItem ci, int fromIndex, int toIndex) {
720             String JavaDoc fromStr = getBundle().getString("CTL_Title")+" "+Integer.toString(fromIndex);
721             if (fromStr.equals(ci.title))
722                 ci.title = getBundle().getString("CTL_Title")+" "+Integer.toString(toIndex);
723         }
724
725         public void writeExternal(ObjectOutput oo) throws IOException {
726             // backward compatibility must be ensured... (table model was implemented using arrays sooner)
727
oo.writeInt(rowCount);
728             int colCount = columns.size();
729             oo.writeInt(colCount);
730
731             String JavaDoc[] titles = new String JavaDoc[colCount];
732             boolean[] editable = new boolean[colCount];
733             for (int i=0; i < colCount; i++) {
734                 ColumnItem ci = (ColumnItem) columns.get(i);
735                 titles[i] = ci.title;
736                 editable[i] = ci.editable;
737             }
738             oo.writeObject(titles);
739             oo.writeObject(editable);
740             for (int i=0; i < colCount; i++) {
741                 ColumnItem ci = (ColumnItem) columns.get(i);
742                 oo.writeObject(ci.type.getName());
743             }
744
745             for (int i=0; i < rowCount; i++)
746                 for (int j=0; j < colCount; j++) {
747                     ColumnItem ci = (ColumnItem) columns.get(j);
748                     if (ci.rows.get(i) instanceof Serializable)
749                         oo.writeObject(ci.rows.get(i));
750                     else
751                         oo.writeObject(null);
752                 }
753         }
754
755         public void readExternal(ObjectInput oi) throws IOException, ClassNotFoundException JavaDoc {
756             // reading is in the previous format (when table model was implemented using arrays)
757
rowCount = oi.readInt();
758             int colCount = oi.readInt();
759
760             columns = new ArrayList(colCount);
761
762             String JavaDoc[] titles = (String JavaDoc[]) oi.readObject();
763             boolean[] editable = (boolean[]) oi.readObject();
764
765             for (int i=0; i < colCount; i++)
766                 columns.add(new ColumnItem(titles[i],Class.forName((String JavaDoc)oi.readObject()),
767                                            editable[i], rowCount));
768
769             for (int i=0; i < rowCount; i++)
770                 for (int j=0; j < colCount; j++) {
771                     ColumnItem ci = (ColumnItem) columns.get(j);
772                     ci.rows.set(i, oi.readObject());
773                 }
774         }
775
776         // helper class for holding data of a column
777
private static class ColumnItem {
778             String JavaDoc title;
779             Class JavaDoc type;
780             boolean editable;
781             java.util.List JavaDoc rows; // values in the column
782

783             ColumnItem(String JavaDoc title, Class JavaDoc type, boolean editable, int rowCount) {
784                 this.title = title;
785                 this.type = type;
786                 this.editable = editable;
787                 rows = new ArrayList(rowCount);
788                 for (int i=0; i < rowCount; i++)
789                     rows.add(null);
790             }
791
792             ColumnItem(String JavaDoc title, Class JavaDoc type, boolean editable, java.util.List JavaDoc data) {
793                 this.title = title;
794                 this.type = type;
795                 this.editable = editable;
796                 rows = data;
797             }
798
799             ColumnItem(ColumnItem ci) {
800                 this.title = ci.title;
801                 this.type = ci.type;
802                 this.editable = ci.editable;
803                 int rowCount = ci.rows.size();
804                 rows = new ArrayList(rowCount);
805
806                 for (int i=0; i < rowCount; i++)
807                     rows.add(ci.rows.get(i));
808             }
809         } // Class ColumnItem
810
} // Class NbTableModel
811

812     // -----------------------------------------------------------------------------
813
// private variables
814

815     private NbTableModel table;
816     private PropertyChangeSupport support;
817 }
818
Popular Tags