KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > jftp > gui > base > dir > TableUtils


1 package net.sf.jftp.gui.base.dir;
2
3 import java.awt.BorderLayout JavaDoc;
4 import java.awt.Component JavaDoc;
5 import java.lang.reflect.Constructor JavaDoc;
6 import java.lang.reflect.Method JavaDoc;
7 import java.util.Vector JavaDoc;
8
9 import javax.swing.DefaultListModel JavaDoc;
10 import javax.swing.ImageIcon JavaDoc;
11 import javax.swing.JComponent JavaDoc;
12 import javax.swing.JLabel JavaDoc;
13 import javax.swing.JList JavaDoc;
14 import javax.swing.JTable JavaDoc;
15 import javax.swing.table.JTableHeader JavaDoc;
16 import javax.swing.table.TableCellRenderer JavaDoc;
17 import javax.swing.table.TableColumn JavaDoc;
18 import javax.swing.table.TableColumnModel JavaDoc;
19 import javax.swing.table.TableModel JavaDoc;
20
21 import net.sf.jftp.config.Settings;
22
23
24 public class TableUtils {
25     
26     
27     /**
28      * Setzt die Breite der TableColumns.
29      *
30      * Quelle: http://www.chka.de/swing/table/cell-sizes.html
31      *
32      * @param table
33      */

34     public static void calcColumnWidths(JTable JavaDoc table)
35     {
36         JTableHeader JavaDoc header = table.getTableHeader();
37
38         TableCellRenderer JavaDoc defaultHeaderRenderer = null;
39
40         if (header != null)
41             defaultHeaderRenderer = header.getDefaultRenderer();
42
43         TableColumnModel JavaDoc columns = table.getColumnModel();
44         TableModel JavaDoc data = table.getModel();
45
46         int margin = columns.getColumnMargin(); // only JDK1.3
47

48         int rowCount = data.getRowCount();
49
50         int totalWidth = 0;
51
52         for (int i = columns.getColumnCount() - 1; i >= 0; --i)
53         {
54             TableColumn JavaDoc column = columns.getColumn(i);
55                 
56             int columnIndex = column.getModelIndex();
57                 
58             int width = -1;
59
60             TableCellRenderer JavaDoc h = column.getHeaderRenderer();
61               
62             if (h == null)
63                 h = defaultHeaderRenderer;
64                 
65             if (h != null) // Not explicitly impossible
66
{
67                 Component JavaDoc c = h.getTableCellRendererComponent
68                        (table, column.getHeaderValue(),
69                         false, false, -1, i);
70                         
71                 width = c.getPreferredSize().width;
72             }
73            
74             for (int row = rowCount - 1; row >= 0; --row)
75             {
76                 TableCellRenderer JavaDoc r = table.getCellRenderer(row, i);
77                      
78                 Component JavaDoc c = r.getTableCellRendererComponent
79                    (table,
80                     data.getValueAt(row, columnIndex),
81                     false, false, row, i);
82             
83                     width = Math.max(width, c.getPreferredSize().width);
84             }
85
86             if (width >= 0)
87                 column.setPreferredWidth(width + margin); // <1.3: without margin
88
else
89                 ; // ???
90

91             totalWidth += column.getPreferredWidth();
92         }
93
94 // only <1.3: totalWidth += columns.getColumnCount() * columns.getColumnMargin();
95

96
97         /* If you like; This does not make sense for two many columns!
98         Dimension size = table.getPreferredScrollableViewportSize();
99
100         size.width = totalWidth;
101
102         table.setPreferredScrollableViewportSize(size);
103         */

104
105         // table.sizeColumnsToFit(-1); <1.3; possibly even table.revalidate()
106

107         // if (header != null)
108
// header.repaint(); only makes sense when the header is visible (only <1.3)
109
}
110     
111     public static void setFixedWidths(JTable JavaDoc table) {
112         JTableHeader JavaDoc header = table.getTableHeader();
113
114         TableCellRenderer JavaDoc defaultHeaderRenderer = null;
115
116         if (header != null)
117             defaultHeaderRenderer = header.getDefaultRenderer();
118
119         TableColumnModel JavaDoc columns = table.getColumnModel();
120         TableModel JavaDoc data = table.getModel();
121
122         int rowCount = data.getRowCount();
123
124         for (int i = 0; i<columns.getColumnCount(); i++)
125         {
126             TableColumn JavaDoc column = columns.getColumn(i);
127             int columnIndex = column.getModelIndex();
128             int width = -1;
129
130             if(i == 0) {
131                 column.setPreferredWidth(20);
132                 column.setMaxWidth(20);
133             }
134             else if(i == 1) {
135                 column.setMinWidth(100);
136                 column.setPreferredWidth(400);
137             }
138             else if(i == 2) {
139                 column.setMinWidth(60);
140                 column.setPreferredWidth(80);
141                 //column.setMaxWidth(90);
142
}
143             else if(i == 3) {
144                 column.setMinWidth(25);
145                 column.setPreferredWidth(25);
146                 //column.setMaxWidth(90);
147
}
148         }
149     }
150     
151     /**
152      * Synchronisiert eine JList mit einem JTable.
153      *
154      * Die Selections werden von dem Table auf die List kopiert.
155      *
156      * @param list
157      * @param listTbl
158      */

159     public static void copyTableSelectionsToJList(JList JavaDoc list, JTable JavaDoc listTbl) {
160         
161         list.setSelectedIndices(new int[0]);
162
163         int rows = listTbl.getRowCount();
164         Vector JavaDoc sel = new Vector JavaDoc();
165         
166         for(int i=0; i<rows; i++) {
167             if(listTbl.getSelectionModel().isSelectedIndex(i)) sel.add(new Integer JavaDoc(i));
168         }
169         
170         int tmp[] = new int[sel.size()];
171         for(int i=0; i<sel.size(); i++) tmp[i] = ((Integer JavaDoc)sel.get(i)).intValue();
172         
173         list.setSelectedIndices(tmp);
174     }
175         
176     /**
177      * Generisches Modell erzeugen.
178      *
179      * JList muss Vektoren von im JTable anzeigbaren Objekten enthalten.
180      *
181      * @param l
182      * @return
183      */

184     private static synchronized TableModel JavaDoc generateTableModel(JList JavaDoc l) {
185         
186           TableModel JavaDoc dataModel = new MaterializedTableModel(l) {
187               
188               public Class JavaDoc getColumnClass(int columnIndex) {
189                     if(columnIndex == 0) return ImageIcon JavaDoc.class;
190                     else if(columnIndex == 3) return JLabel JavaDoc.class;
191                     else return String JavaDoc.class;
192               }
193               
194               public int getColumnCount() {
195                   //return (list.getModel().getSize() > 0 ? ((Vector)list.getModel().getElementAt(0)).size() : 0);
196
return 4;
197               }
198               
199               public int getRowCount() {
200                   return list.getModel().getSize();
201               }
202               
203               public Object JavaDoc getValueAt(int row, int col) {
204
205                   if(list.getModel().getSize() == 0) return ""+null;
206
207                   DirEntry ret = (DirEntry) list.getModel().getElementAt(row);
208                   
209                   if(col == 0) return ret.getImageIcon();
210                   else if(col == 1) return ret.toString();
211                   else if(col == 2) {
212                       String JavaDoc tmp = ""+ret.getFileSize();
213                       String JavaDoc r = tmp.replaceAll(" >", "");
214                       return r;
215                   }
216                   else if(col == 3) {
217                       return ret;
218                   }
219
220
221                   //System.out.println(">>> "+ret.get(col)+" -> "+(ret.get(col) instanceof Status));
222

223                   //return ret.size() > col ? ret.get(col) : "<ERROR>";
224
return ret;
225               }
226           };
227
228           return dataModel;
229     }
230     
231     
232     /**
233      * F?hrt Updates auf einen beliebigen JTable durch.
234      *
235      * list muss hierzu vom Typ Vector<String> sein.
236      *
237      * @param list
238      * @param listTbl
239      */

240     public static void layoutTable(JList JavaDoc list, JTable JavaDoc listTbl) {
241         layoutTable(list, listTbl, null);
242     }
243     
244     /**
245      * F?hrt Updates auf einen beliebigen JTable durch.
246      *
247      * list muss hierzu vom Typ Vector<String> sein.
248      */

249     public static void layoutTable(JList JavaDoc list, JTable JavaDoc listTbl, Vector JavaDoc names) {
250             listTbl.setModel(generateTableModel(list));
251             
252             if(Settings.useFixedTableWidths) {
253                 setFixedWidths(listTbl);
254             }
255             else {
256                 calcColumnWidths(listTbl);
257             }
258             
259             if(names != null) modifyTableHeader(listTbl.getTableHeader(), names);
260             
261             // 1.6+ only
262
tryToEnableRowSorting(listTbl);
263             
264             //listTbl.doLayout();
265
}
266     
267     /**
268      * Versucht ?ber die Java-Reflection-API das automatische JTable-sort zu aktivieren.
269      *
270      * Das Feature ist neu in JDK1.6 und erlaubt es dem Benutzer durch Clicks auf die
271      * jeweiligen Tabellenspalten Zeilen automatisch zu sortieren.
272      *
273      * @param listTbl JTable
274      */

275     public static void tryToEnableRowSorting(JTable JavaDoc listTbl) {
276         /*
277         try {
278             TableModel mdl = listTbl.getModel();
279             Class c = Class.forName("javax.swing.table.TableRowSorter");
280             Class c2 = Class.forName("javax.swing.RowSorter");
281             
282             Constructor con = c.getConstructor(TableModel.class);
283             
284             Object args[] = new Object[1];
285             args[0] = mdl;
286                         
287             Method meth = listTbl.getClass().getMethod("setRowSorter", c2);
288             Object retobj = meth.invoke(listTbl, con.newInstance(args));
289             
290             Settings.IS_JAVA_1_6 = true;
291             
292         // System.out.println("JTable-Sortierung wurde aktiviert.");
293         }
294         catch(Exception e) {
295         // System.out.println("JTable-Sortierung konnte nicht aktiviert werden.");
296         }
297         catch(Error ex) {
298         // System.out.println("JTable-Sortierung konnte nicht aktiviert werden.");
299         }
300         */

301     }
302     
303     /**
304      * Setzt den Header einer JTable
305      * @param head
306      * @param columnNames
307      */

308     public static void modifyTableHeader(JTableHeader JavaDoc head, Vector JavaDoc columnNames) {
309         
310         TableColumnModel JavaDoc m = head.getColumnModel();
311         
312         if(m.getColumnCount() != columnNames.size()) {
313             System.out.println("Column mismatch: "+m.getColumnCount()+"/"+columnNames.size());
314             return;
315         }
316         
317         for(int i=0; i<columnNames.size(); i++) {
318             TableColumn JavaDoc c = m.getColumn(i);
319             c.sizeWidthToFit();
320             c.setHeaderValue(columnNames.get(i));
321         }
322     }
323     
324     /**
325      * Erzeugt einen Panel mit View und Header eines JTables.
326      *
327      */

328     public static JComponent JavaDoc makeTable(JTable JavaDoc table, JComponent JavaDoc cont) {
329         JTableHeader JavaDoc header = table.getTableHeader();
330         
331         cont.setLayout(new BorderLayout JavaDoc());
332         cont.add(header, BorderLayout.NORTH);
333         cont.add(table, BorderLayout.CENTER);
334         
335         return cont;
336     }
337     
338 }
339
Popular Tags