View Javadoc

1   package com.melloware.jukes.gui.view.component;
2   
3   import java.awt.Color;
4   import java.awt.Component;
5   import java.awt.event.ActionEvent;
6   import java.awt.event.MouseAdapter;
7   import java.awt.event.MouseEvent;
8   import java.io.File;
9   import java.io.FileWriter;
10  import java.io.IOException;
11  import java.util.Enumeration;
12  
13  import javax.swing.AbstractAction;
14  import javax.swing.Icon;
15  import javax.swing.JFileChooser;
16  import javax.swing.JMenuItem;
17  import javax.swing.JPopupMenu;
18  import javax.swing.JTable;
19  import javax.swing.ListSelectionModel;
20  import javax.swing.table.TableCellRenderer;
21  import javax.swing.table.TableColumn;
22  import javax.swing.table.TableColumnModel;
23  import javax.swing.table.TableModel;
24  
25  import org.apache.commons.logging.Log;
26  import org.apache.commons.logging.LogFactory;
27  
28  import com.melloware.jukes.exception.InfrastructureException;
29  import com.melloware.jukes.file.filter.FilterFactory;
30  import com.melloware.jukes.gui.tool.Resources;
31  import com.melloware.jukes.util.MessageUtil;
32  
33  /**
34   * Abtsract base table that can export its results alternates row colors, and
35   * allows customization of right click popup menu.
36   * <p>
37   * Copyright (c) 1999-2007 Melloware, Inc. <http://www.melloware.com>
38   * @author Emil A. Lefkof III <info@melloware.com>
39   * @version 4.0
40   */
41  public final class ExportableTable
42      extends JTable {
43  
44      private static final Log LOG = LogFactory.getLog(ExportableTable.class);
45      private static Icon csvIcon = Resources.CSV_ICON;
46      private static String csvText = "Export To CSV";
47      private boolean popupEnabled = true;
48      // private static Icon pdfIcon = Resources.PDF_ICON;
49      // private static String pdfText = "Export To PDF";
50      private Color evenColor = Color.WHITE;
51      private Color oddColor = new Color(0xee, 0xee, 0xff);
52      private JPopupMenu popupMenu = null;
53  
54      public ExportableTable() {
55          super();
56          constructor();
57      }
58  
59      public ExportableTable(TableModel dm) {
60          super(dm);
61          constructor();
62      }
63  
64      public ExportableTable(TableModel dm, TableColumnModel cm) {
65          super(dm, cm);
66          constructor();
67      }
68  
69      public ExportableTable(int numRows, int numColumns) {
70          super(numRows, numColumns);
71          constructor();
72      }
73  
74  
75      public ExportableTable(Object[][] rowData, Object[] columnNames) {
76          super(rowData, columnNames);
77          constructor();
78      }
79  
80      public ExportableTable(TableModel dm, TableColumnModel cm, ListSelectionModel sm) {
81          super(dm, cm, sm);
82          constructor();
83      }
84  
85      /**
86       * Gets the evenColor.
87       * <p>
88       * @return Returns the evenColor.
89       */
90      public Color getEvenColor() {
91          return this.evenColor;
92      }
93  
94      /**
95       * Gets the oddColor.
96       * <p>
97       * @return Returns the oddColor.
98       */
99      public Color getOddColor() {
100         return this.oddColor;
101     }
102 
103     /**
104      * Sets the evenColor.
105      * <p>
106      * @param aEvenColor The evenColor to set.
107      */
108     public void setEvenColor(Color aEvenColor) {
109         this.evenColor = aEvenColor;
110     }
111 
112     /**
113      * Sets the oddColor.
114      * <p>
115      * @param aOddColor The oddColor to set.
116      */
117     public void setOddColor(Color aOddColor) {
118         this.oddColor = aOddColor;
119     }
120 
121     /**
122      * Allows the customization of the popup menu
123      * @param popup - This is a prebuilt popup menu that can be modified
124      */
125     public void addPopupMenu(JPopupMenu popup) {
126         this.popupMenu.addSeparator();
127         Component[] items = popup.getComponents();
128         for (int i = 0; i < items.length; i++) {
129             this.popupMenu.add(items[i]);
130         }
131     }
132 
133     public void enablePopupMenu(boolean enabled) {
134         popupEnabled = enabled;
135     }
136 
137     /**
138      * Change even and odd rows to white and light blue.
139      */
140     public Component prepareRenderer(TableCellRenderer aRenderer, int aRow, int aColumn) {
141         final Component component = super.prepareRenderer(aRenderer, aRow, aColumn);
142         if (!isRowSelected(aRow)) {
143             component.setBackground(((aRow % 2) == 0) ? getEvenColor() : getOddColor());
144         }
145         return component;
146     }
147 
148     public void stopEditing() {
149         if (cellEditor != null) {
150             cellEditor.stopCellEditing();
151         }
152     }
153 
154     /**
155      * Stores the table as a comma seperated values file.
156      * <p>
157      * @param isSelected if the row is selected
158      */
159     /**
160      * @param isSelected
161      */
162     protected void storeTableAsCSV(boolean isSelected) {
163         if (isSelected && (this.getSelectedRowCount() == 0)) {
164             return;
165         }
166 
167         final StringBuffer sb = new StringBuffer("\"");
168         final TableColumnModel cm = this.getColumnModel();
169         final Enumeration enumeration = cm.getColumns();
170         while (enumeration.hasMoreElements()) {
171             final TableColumn tc = (TableColumn)enumeration.nextElement();
172             sb.append(tc.getHeaderValue().toString());
173             if (enumeration.hasMoreElements()) {
174                 sb.append("\",\"");
175             } else {
176                 sb.append("\"\n");
177             }
178         }
179 
180         final int rowCount = this.getRowCount();
181         final int colCount = this.getColumnCount();
182         for (int i = 0; i < rowCount; i++) {
183             sb.append('"');
184             for (int j = 0; j < colCount; j++) {
185                 if (!isSelected || this.isCellSelected(i, j)) {
186                     if (this.getValueAt(i, j) == null) {
187                         sb.append("");
188                     } else {
189                         String value = this.getValueAt(i, j).toString().replace(',', ' ');
190                         sb.append(value);
191                     }
192                     if (j == (colCount - 1)) {
193                         sb.append("\"\n");
194                     } else {
195                         sb.append("\",\"");
196                     }
197                 }
198             }
199         }
200 
201         final JFileChooser chooser = new JFileChooser();
202         chooser.setDialogTitle("Export Results");
203         chooser.setFileFilter(FilterFactory.csvFileFilter());
204         chooser.setMultiSelectionEnabled(false);
205         chooser.setFileHidingEnabled(true);
206         final int returnVal = chooser.showSaveDialog(this);
207         if (returnVal != JFileChooser.APPROVE_OPTION) {
208             return;
209         }
210         File file = chooser.getSelectedFile();
211         if (LOG.isDebugEnabled()) {
212             LOG.debug("Absolute: " + file.getAbsolutePath());
213         }
214 
215         // add the extension if missing
216         file = FilterFactory.forceCsvExtension(file);
217 
218         try {
219             final FileWriter writer = new FileWriter(file);
220             writer.write(sb.toString());
221             writer.close();
222 
223             MessageUtil.showInformation(this, "Table exported successfully.");
224         } catch (IOException ex) {
225             LOG.error("Error writing file: \n\n" + ex.getMessage(), ex);
226         } catch (InfrastructureException ex) {
227             LOG.error("Error writing file: \n\n" + ex.getMessage(), ex);
228         } catch (Exception ex) {
229             LOG.error("Unexpected error writing file.", ex);
230         }
231     }
232 
233     // protected void storeTableAsPDF(boolean isSelected) {
234     // int rowCount = this.getRowCount();
235     // int colCount = this.getColumnCount();
236     //
237     // if (isSelected && (this.getSelectedRowCount() == 0)) {
238     // return;
239     // }
240     //
241     // Document document = null;
242     // try {
243     // final PdfPTable datatable = new PdfPTable(colCount);
244     //
245     // datatable.getDefaultCell().setPadding(3);
246     // // int headerwidths[] = {
247     // // 9, 4, 8, 10, 8, 11, 9, 7, 9, 10, 4, 10}; // percentage
248     // // datatable.setWidths(headerwidths);
249     // datatable.setWidthPercentage(100);    // percentage
250     //
251     // datatable.getDefaultCell().setBorderWidth(2);
252     // datatable.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
253     //
254     // final TableColumnModel cm = this.getColumnModel();
255     // final Enumeration enumeration = cm.getColumns();
256     // while (enumeration.hasMoreElements()) {
257     // TableColumn tc = (TableColumn)enumeration.nextElement();
258     // datatable.addCell(tc.getHeaderValue().toString());
259     // }
260     //
261     // datatable.setHeaderRows(1);    // this is the end of the table header
262     // datatable.getDefaultCell().setBorderWidth(1);
263     //
264     // for (int i = 0; i < rowCount; i++) {
265     // if ((i % 2) == 1) {
266     // datatable.getDefaultCell().setGrayFill(0.9f);
267     // }
268     // for (int j = 0; j < colCount; j++) {
269     // if (!isSelected || this.isCellSelected(i, j)) {
270     // if (this.getValueAt(i, j) == null) {
271     // datatable.addCell("");
272     // } else {
273     // String value = this.getValueAt(i, j).toString().replace(',', ' ');
274     // datatable.addCell(value);
275     // }
276     // }
277     // }
278     // if ((i % 2) == 1) {
279     // datatable.getDefaultCell().setGrayFill(0.0f);
280     // }
281     // }
282     //
283     // final JFileChooser chooser = new JFileChooser();
284     // chooser.setDialogTitle("Export Results");
285     // chooser.setFileFilter(FilterFactory.pdfFileFilter());
286     // chooser.setMultiSelectionEnabled(false);
287     // chooser.setFileHidingEnabled(true);
288     // final int returnVal = chooser.showSaveDialog(this);
289     // if (returnVal != JFileChooser.APPROVE_OPTION) {
290     // return;
291     // }
292     // File file = chooser.getSelectedFile();
293     // if (LOG.isDebugEnabled()) {
294     // LOG.debug("Absolute: " + file.getAbsolutePath());
295     // }
296     //
297     // // add the extension if missing
298     // file = FilterFactory.forcePdfExtension(file);
299     //
300     // // new document
301     // document = new Document(PageSize.A4.rotate(), 10, 10, 10, 10);
302     // // create a writer that listens to the document
303     // PdfWriter.getInstance(document, new FileOutputStream(file));
304     // // open the document
305     // document.open();
306     // // add content to the document (this happens in a seperate method)
307     // document.add(datatable);
308     //
309     // // close the document
310     // document.close();
311     //
312     // MessageUtil.showInformation(this, "Table exported successfully.");
313     // } catch (IOException ex) {
314     // LOG.error("Error writing file: \n\n" + ex.getMessage(), ex);
315     // } catch (InfrastructureException ex) {
316     // LOG.error("Error writing file: \n\n" + ex.getMessage(), ex);
317     // } catch (Exception ex) {
318     // LOG.error("Unexpected error writing file.", ex);
319     // }
320     //
321     // }
322 
323     private JPopupMenu buildPopupMenu() {
324         final JPopupMenu pop = new JPopupMenu("Menu");
325         final AbstractAction storeAsCSVAction = new AbstractAction(csvText, csvIcon) {
326             public void actionPerformed(ActionEvent event) {
327                 storeTableAsCSV(false);
328             }
329         };
330         // AbstractAction storeAsPDFAction = new AbstractAction(pdfText, pdfIcon) {
331         // public void actionPerformed(ActionEvent event) {
332         // storeTableAsPDF(false);
333         // }
334         // };
335 
336         final JMenuItem item = new JMenuItem(storeAsCSVAction);
337         pop.add(item);
338         // item = new JMenuItem(storeAsPDFAction);
339         // pop.add(item);
340 
341         pop.setLabel("");
342         this.addMouseListener(new MousePopupListener());
343         return pop;
344     }
345 
346     private void constructor() {
347         popupMenu = buildPopupMenu();
348     }
349 
350     private class MousePopupListener
351         extends MouseAdapter {
352 
353         public void mouseClicked(MouseEvent e) {
354             checkPopup(e);
355         }
356 
357         public void mousePressed(MouseEvent e) {
358             checkPopup(e);
359         }
360 
361         public void mouseReleased(MouseEvent e) {
362             checkPopup(e);
363         }
364 
365         private void checkPopup(MouseEvent e) {
366             if ((e.isPopupTrigger()) && (popupEnabled)) {
367                 popupMenu.show(ExportableTable.this, e.getX(), e.getY());
368             }
369         }
370     }
371 }