View Javadoc

1   /*
2    * 
3    * 
4    */
5   package oscon2006.swing;
6   
7   import java.awt.event.ActionEvent;
8   import java.io.File;
9   import java.io.FileOutputStream;
10  import javax.swing.*;
11  import oscon2006.common.XlsBuilder;
12  
13  public class SaveTableAction extends AbstractAction
14  {
15  	
16  	private final JTable table;
17  	
18  	public SaveTableAction(JTable t)
19  	{
20  		super("Save table...");
21  		this.table = t;
22  	}
23  	
24  	public void actionPerformed(ActionEvent e)
25  	{
26  		JFileChooser chooser = new JFileChooser("/demo");
27  		chooser.setSelectedFile(new File("table.xls"));
28  		chooser.setFileFilter(new XlsFileFilter());
29  		chooser.showSaveDialog(null);
30  		File f = chooser.getSelectedFile();
31  		if (f != null)
32  		{
33  			FileOutputStream fos = null;
34  			try
35  			{
36  				f.delete();
37  				fos = new FileOutputStream(f);
38  				XlsBuilder builder = new XlsBuilder();
39  				builder.setData(table.getModel());
40  				builder.build(fos);
41  				fos.flush();
42  				fos.close();
43  			}
44  			catch (Exception ex)
45  			{
46  				ex.printStackTrace();
47  				JOptionPane.showMessageDialog(null, 
48  								"An error occurred while saving the file.", 
49  								"Error", 
50  								JOptionPane.ERROR_MESSAGE);	
51  			}
52  		}
53  			
54  	}
55  
56  }