summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java
blob: 2e1394905427213643ec4c948f03297917c16e81 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package bjc.utils.gui.awt;

import java.awt.FileDialog;
import java.awt.Frame;
import java.io.File;
import java.io.FilenameFilter;

import bjc.utils.gui.SimpleDialogs;

/**
 * A simple way to get the user to pick a file
 * 
 * Built for AWT.
 * 
 * @author ben
 *
 */
public class SimpleFileDialog {
	/**
	 * Prompt the user to pick a file to open
	 * 
	 * @param par
	 *            The parent of the file picker
	 * @param title
	 *            The title of the file picker
	 * @param extensions
	 *            The extensions to accept as valid
	 * @return The file the user picked
	 */
	public static File getOpenFile(Frame par, String title,
			String... extensions) {
		FileDialog fd = new FileDialog(par, title, FileDialog.LOAD);

		if (extensions != null) {
			FilenameFilter filter = new ExtensionFileFilter(extensions);
			fd.setFilenameFilter(filter);
		}

		fd.setVisible(true);

		while (fd.getFile() == null) {
			SimpleDialogs.showError(par, "File I/O Error",
					"Please choose a file to open.");
			fd.setVisible(true);
		}

		return fd.getFiles()[0];
	}

	/**
	 * Prompt the user to pick a file to open
	 * 
	 * @param par
	 *            The parent of the file picker
	 * @param title
	 *            The title of the file picker
	 * @return The file the user picked
	 */
	public static File getOpenFile(Frame par, String title) {
		return getOpenFile(par, title, (String[]) null);
	}

	/**
	 * Prompt the user to pick a file to save
	 * 
	 * @param par
	 *            The parent of the file picker
	 * @param title
	 *            The title of the file picker
	 * @param extensions
	 *            The extensions to accept as valid
	 * @return The file the user picked
	 */
	public static File getSaveFile(Frame par, String title,
			String... extensions) {
		FileDialog fd = new FileDialog(par, title, FileDialog.SAVE);

		if (extensions != null) {
			FilenameFilter filter = new ExtensionFileFilter(extensions);
			fd.setFilenameFilter(filter);
		}

		fd.setVisible(true);

		while (fd.getFile() == null) {
			SimpleDialogs.showError(par, "File I/O Error",
					"Please choose a file to save to.");
			fd.setVisible(true);
		}

		return fd.getFiles()[0];
	}

	/**
	 * Prompt the user to pick a file to save
	 * 
	 * @param par
	 *            The parent of the file picker
	 * @param title
	 *            The title of the file picker
	 * @return The file the user picked
	 */
	public static File getSaveFile(Frame par, String title) {
		return getSaveFile(par, title, (String[]) null);
	}
}