KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > poi > hssf > contrib > view > SViewerPanel


1
2 /* ====================================================================
3    Copyright 2002-2004 Apache Software Foundation
4
5    Licensed under the Apache License, Version 2.0 (the "License");
6    you may not use this file except in compliance with the License.
7    You may obtain a copy of the License at
8
9        http://www.apache.org/licenses/LICENSE-2.0
10
11    Unless required by applicable law or agreed to in writing, software
12    distributed under the License is distributed on an "AS IS" BASIS,
13    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14    See the License for the specific language governing permissions and
15    limitations under the License.
16 ==================================================================== */

17         
18
19
20 package org.apache.poi.hssf.contrib.view;
21
22 import java.awt.*;
23 import java.awt.event.*;
24 import java.io.*;
25 import javax.swing.*;
26 import javax.swing.table.*;
27 import javax.swing.event.*;
28
29 import org.apache.poi.hssf.usermodel.*;
30
31 /**
32  * This class presents the sheets to the user.
33  *
34  *
35  * @author Andrew C. Oliver
36  * @author Jason Height
37  */

38 public class SViewerPanel extends JPanel {
39   /** This field is the magic number to convert from a Character width to a
40    * java pixel width.
41    *
42    * When the "normal" font size in a workbook changes, this effects all
43    * of the heights and widths. Unfortunately there is no way to retrieve this
44    * information, hence the MAGIC number.
45    *
46    * This number may only work for the normal style font size of Arial size 10.
47    *
48    */

49   private static final int magicCharFactor = 7;
50   /** Reference to the woorkbook that is being displayed*/
51   private HSSFWorkbook wb;
52   /** Reference to the tabs component*/
53   private JTabbedPane sheetPane;
54   /** Reference to the cell renderer that is used to render all cells*/
55   private SVTableCellRenderer cellRenderer;
56   /** Reference to the cell editor that is used to edit all cells.
57    * Only constructed if editing is allowed
58    */

59   private SVTableCellEditor cellEditor;
60   /** Flag indicating if editing is allowed. Otherwise the viewer is in
61    * view only mode.
62    */

63   private boolean allowEdits;
64
65   /**Construct the representation of the workbook*/
66   public SViewerPanel(HSSFWorkbook wb, boolean allowEdits) {
67     this.wb = wb;
68     this.allowEdits = allowEdits;
69
70     initialiseGui();
71   }
72
73   private void initialiseGui() {
74     cellRenderer = new SVTableCellRenderer(this.wb);
75     if (allowEdits)
76       cellEditor = new SVTableCellEditor(this.wb);
77
78     //Initialise the Panel
79
sheetPane = new JTabbedPane(JTabbedPane.BOTTOM);
80
81     if (allowEdits)
82       sheetPane.addMouseListener(createTabListener());
83     int sheetCount = wb.getNumberOfSheets();
84     for (int i=0; i<sheetCount;i++) {
85       String JavaDoc sheetName = wb.getSheetName(i);
86       //Add the new sheet to the tabbed pane
87
sheetPane.addTab(sheetName, makeSheetView(wb.getSheetAt(i)));
88     }
89     setLayout(new BorderLayout());
90     add(sheetPane, BorderLayout.CENTER);
91   }
92
93   protected JComponent makeSheetView(HSSFSheet sheet) {
94     JTable sheetView = new JTable(new SVTableModel(sheet));
95     sheetView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
96     sheetView.setDefaultRenderer(HSSFCell.class, cellRenderer);
97     if (allowEdits)
98       sheetView.setDefaultEditor(HSSFCell.class, cellEditor);
99     JTableHeader header = sheetView.getTableHeader();
100     //Dont allow column reordering
101
header.setReorderingAllowed(false);
102     //Only allow column resizing if editing is allowed
103
header.setResizingAllowed(allowEdits);
104
105     //Set the columns the correct size
106
TableColumnModel columns = sheetView.getColumnModel();
107     for (int i=0; i< columns.getColumnCount(); i++) {
108       TableColumn column = columns.getColumn(i);
109       short width = sheet.getColumnWidth((short)i);
110       //256 is because the width is in 256ths of a character
111
column.setPreferredWidth(width/256*magicCharFactor);
112     }
113
114     //Set the rows to the correct size
115
int rows = sheet.getPhysicalNumberOfRows();
116     Insets insets = cellRenderer.getInsets();
117     //Need to include the insets in the calculation of the row height to use.
118
int extraHeight = insets.bottom+insets.top;
119     for (int i=0; i< rows; i++) {
120       HSSFRow row = sheet.getRow(i);
121       if (row == null) {
122         sheetView.setRowHeight(i, (int)sheet.getDefaultRowHeightInPoints()+extraHeight);
123       } else {
124         sheetView.setRowHeight(i, (int)row.getHeightInPoints()+extraHeight);
125       }
126     }
127
128     //Add the row header to the sheet
129
SVRowHeader rowHeader = new SVRowHeader(sheet, sheetView, extraHeight);
130     JScrollPane scroll = new JScrollPane( sheetView );
131     scroll.setRowHeaderView(rowHeader);
132     return scroll;
133   }
134
135   public void paint(Graphics g) {
136     //JMH I am only overriding this to get a picture of the time taken to paint
137
long start = System.currentTimeMillis();
138     super.paint(g);
139     long elapsed = System.currentTimeMillis()-start;
140     System.out.println("Paint time = "+elapsed);
141   }
142
143   protected MouseListener createTabListener() {
144     return new TabListener();
145   }
146
147   /** This class defines the default MouseListener that listens to
148    * mouse events in the tabbed pane
149    *
150    * The default is to popup a menu when the event occurs over a tab
151    */

152   private class TabListener implements MouseListener {
153     public JPopupMenu popup;
154     public TabListener() {
155       popup = new JPopupMenu("Sheet");
156       popup.add(createInsertSheetAction());
157       popup.add(createDeleteSheetAction());
158       popup.add(createRenameSheetAction());
159     }
160
161     protected Action createInsertSheetAction() {
162       return new InsertSheetAction();
163     }
164
165     protected Action createDeleteSheetAction() {
166       return new DeleteSheetAction();
167     }
168
169     protected Action createRenameSheetAction() {
170       return new RenameSheetAction();
171     }
172
173
174     /** This method will display the popup if the mouseevent is a popup event
175      * and the event occurred over a tab
176      */

177     protected void checkPopup(MouseEvent e) {
178       if (e.isPopupTrigger()) {
179         int tab = sheetPane.getUI().tabForCoordinate(sheetPane, e.getX(), e.getY());
180         if (tab != -1) {
181           popup.show(sheetPane, e.getX(), e.getY());
182         }
183       }
184     }
185
186     public void mouseClicked(MouseEvent e) {
187       checkPopup(e);
188     }
189
190     public void mousePressed(MouseEvent e) {
191       checkPopup(e);
192     }
193
194     public void mouseReleased(MouseEvent e) {
195       checkPopup(e);
196     }
197
198     public void mouseEntered(MouseEvent e) {}
199     public void mouseExited(MouseEvent e) {}
200   }
201
202   /** This class defines the action that is performed when the sheet is renamed*/
203   private class RenameSheetAction extends AbstractAction {
204     public RenameSheetAction() {
205       super("Rename");
206     }
207
208     public void actionPerformed(ActionEvent e) {
209       int tabIndex = sheetPane.getSelectedIndex();
210       if (tabIndex != -1) {
211         String JavaDoc newSheetName = (String JavaDoc)JOptionPane.showInputDialog(sheetPane, "Enter a new Sheetname", "Rename Sheet", JOptionPane.QUESTION_MESSAGE);
212         if (newSheetName != null) {
213           wb.setSheetName(tabIndex, newSheetName);
214           sheetPane.setTitleAt(tabIndex, newSheetName);
215         }
216       }
217     }
218   }
219
220   /** This class defines the action that is performed when a sheet is inserted*/
221   private class InsertSheetAction extends AbstractAction {
222     public InsertSheetAction() {
223       super("Insert");
224     }
225
226     public void actionPerformed(ActionEvent e) {
227       //Create a new sheet then search for the sheet and make sure that the
228
//sheetPane shows it.
229
HSSFSheet newSheet = wb.createSheet();
230       for (int i=0; i<wb.getNumberOfSheets();i++) {
231         HSSFSheet sheet = wb.getSheetAt(i);
232         if (newSheet == sheet) {
233           sheetPane.insertTab(wb.getSheetName(i), null, makeSheetView(sheet), null, i);
234         }
235       }
236     }
237   }
238
239   /** This class defines the action that is performed when the sheet is deleted*/
240   private class DeleteSheetAction extends AbstractAction {
241     public DeleteSheetAction() {
242       super("Delete");
243     }
244
245     public void actionPerformed(ActionEvent e) {
246       int tabIndex = sheetPane.getSelectedIndex();
247       if (tabIndex != -1) {
248         if (JOptionPane.showConfirmDialog(sheetPane, "Are you sure that you want to delete the selected sheet", "Delete Sheet?", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
249           wb.removeSheetAt(tabIndex);
250           sheetPane.remove(tabIndex);
251         }
252       }
253     }
254   }
255
256   public boolean isEditable() {
257     return allowEdits;
258   }
259
260   /**Main method*/
261   public static void main(String JavaDoc[] args) {
262     try {
263       FileInputStream in = new FileInputStream(args[0]);
264       HSSFWorkbook wb = new HSSFWorkbook(in);
265       in.close();
266
267       SViewerPanel p = new SViewerPanel(wb, true);
268       JFrame frame;
269       frame = new JFrame() {
270         protected void processWindowEvent(WindowEvent e) {
271           super.processWindowEvent(e);
272           if (e.getID() == WindowEvent.WINDOW_CLOSING) {
273             System.exit(0);
274           }
275         }
276         public synchronized void setTitle(String JavaDoc title) {
277           super.setTitle(title);
278           enableEvents(AWTEvent.WINDOW_EVENT_MASK);
279         }
280       };
281       frame.setTitle("Viewer Frame");
282       frame.getContentPane().add(p, BorderLayout.CENTER);
283       frame.setSize(800,640);
284       Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
285       frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
286       frame.setVisible(true);
287     } catch (IOException ex) {
288       ex.printStackTrace();
289       System.exit(1);
290     }
291   }
292 }
293
Popular Tags