1 package net.sourceforge.jpotpourri.gui.chooser;
2
3
4 import java.io.File;
5 import java.util.Arrays;
6 import java.util.LinkedHashSet;
7 import java.util.Set;
8
9 import javax.swing.JFileChooser;
10 import javax.swing.filechooser.FileFilter;
11
12 import net.sourceforge.jpotpourri.util.CollectionUtil;
13 import net.sourceforge.jpotpourri.util.FileUtil;
14
15
16
17
18
19
20 public class FileChooser extends AbstractFileDirectoryChooser {
21
22
23
24 private static final long serialVersionUID = 4870536517103469362L;
25
26 private final FileFilter fileFilter;
27
28
29
30 public FileChooser(final String dialogTitle, final String... validExtensions) {
31 this(dialogTitle, AbstractFileDirectoryChooser.DEFAULT_BUTTON_LABEL, null,
32 AbstractFileDirectoryChooser.DEFAULT_BUTTON_POSITION, validExtensions);
33 }
34
35
36 public FileChooser(final String dialogTitle, final ButtonPosition position, final String... validExtensions) {
37 this(dialogTitle, AbstractFileDirectoryChooser.DEFAULT_BUTTON_LABEL, null,
38 position, validExtensions);
39 }
40
41
42 public FileChooser(final String dialogTitle, final File defaultPath,
43 final ButtonPosition position, final String... validExtensions) {
44 this(dialogTitle, AbstractFileDirectoryChooser.DEFAULT_BUTTON_LABEL, defaultPath, position, validExtensions);
45 }
46
47
48 public FileChooser(final String dialogTitle, final String buttonLabel,
49 final File defaultPath, final ButtonPosition position, final String... validExtensions) {
50 super(dialogTitle, defaultPath, position, buttonLabel);
51
52 final Set<String> validExtensionsSet = new LinkedHashSet<String>(Arrays.asList(validExtensions));
53 final String validExtensionsString = CollectionUtil.toString(validExtensionsSet);
54
55 this.fileFilter = new FileFilter() {
56 @Override
57 public boolean accept(final File file) {
58 if (file.isDirectory() == true) {
59 return true;
60 }
61
62 final String extension = FileUtil.extractExtension(file);
63 if (extension == null) {
64 return false;
65 }
66
67 return validExtensionsSet.contains(extension);
68 }
69 @Override
70 public String getDescription() {
71 return validExtensionsString;
72 }
73 };
74 }
75
76
77
78
79 public final File getSelectedFile() {
80 return this.getFileOrDir();
81 }
82
83 @Override
84 final int getSelectionMode() {
85 return JFileChooser.FILES_ONLY;
86 }
87
88 @Override
89 final FileFilter getFileFilter() {
90 return this.fileFilter;
91 }
92
93 @Override
94 final boolean isRightFileOrDir(final File file) {
95 return file.isFile();
96 }
97
98 public final void setFile(final File file) {
99 this.setFileOrDir(file);
100 }
101
102 @Override
103 final String getFileDirName() {
104 return "File";
105 }
106 }