| 1 | /** |
|---|
| 2 | * @(#)SaveFileDialogExample.java 1.0 |
|---|
| 3 | * This code is written by www.codejava.net |
|---|
| 4 | * |
|---|
| 5 | */ |
|---|
| 6 | |
|---|
| 7 | import java.awt.FlowLayout; |
|---|
| 8 | import java.awt.event.ActionEvent; |
|---|
| 9 | import java.awt.event.ActionListener; |
|---|
| 10 | import java.io.File; |
|---|
| 11 | |
|---|
| 12 | import javax.swing.JButton; |
|---|
| 13 | import javax.swing.JFileChooser; |
|---|
| 14 | import javax.swing.JFrame; |
|---|
| 15 | import javax.swing.SwingUtilities; |
|---|
| 16 | import javax.swing.UIManager; |
|---|
| 17 | |
|---|
| 18 | public class SaveFileDialogExample extends JFrame { |
|---|
| 19 | |
|---|
| 20 | private JButton buttonBrowse; |
|---|
| 21 | |
|---|
| 22 | public SaveFileDialogExample() { |
|---|
| 23 | super("Save File Dialog Example"); |
|---|
| 24 | setLayout(new FlowLayout()); |
|---|
| 25 | buttonBrowse = new JButton("Save..."); |
|---|
| 26 | buttonBrowse.addActionListener(new ActionListener() { |
|---|
| 27 | |
|---|
| 28 | public void actionPerformed(ActionEvent arg0) { |
|---|
| 29 | showSaveFileDialog(); |
|---|
| 30 | } |
|---|
| 31 | }); |
|---|
| 32 | getContentPane().add(buttonBrowse); |
|---|
| 33 | setSize(300, 100); |
|---|
| 34 | setLocationRelativeTo(null); |
|---|
| 35 | setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
|---|
| 36 | setVisible(true); |
|---|
| 37 | } |
|---|
| 38 | |
|---|
| 39 | public static void main(String[] args) { |
|---|
| 40 | try { |
|---|
| 41 | UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); |
|---|
| 42 | } catch (Exception e) { } |
|---|
| 43 | |
|---|
| 44 | SwingUtilities.invokeLater(new Runnable() { |
|---|
| 45 | |
|---|
| 46 | public void run() { |
|---|
| 47 | new SaveFileDialogExample(); |
|---|
| 48 | } |
|---|
| 49 | }); |
|---|
| 50 | } |
|---|
| 51 | |
|---|
| 52 | private void showSaveFileDialog() { |
|---|
| 53 | String fs = System.getProperty("file.separator"); |
|---|
| 54 | JFileChooser fileChooser = new JFileChooser(); |
|---|
| 55 | fileChooser.setDialogTitle("Specify a file to save"); |
|---|
| 56 | fileChooser.setSelectedFile(new File("" + System.getProperty("user.dir") |
|---|
| 57 | + fs + "Incidents" + fs + "inc_123.xml")); |
|---|
| 58 | |
|---|
| 59 | int userSelection = fileChooser.showSaveDialog(this); |
|---|
| 60 | if (userSelection == JFileChooser.APPROVE_OPTION) { |
|---|
| 61 | File fileToSave = fileChooser.getSelectedFile(); |
|---|
| 62 | System.out.println("Save as file: " + fileToSave.getAbsolutePath()); |
|---|
| 63 | } |
|---|
| 64 | } |
|---|
| 65 | } |
|---|