1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.github.tonywasher.joceanus.tethys.swing.dialog;
18
19 import io.github.tonywasher.joceanus.oceanus.logger.OceanusLogManager;
20 import io.github.tonywasher.joceanus.oceanus.logger.OceanusLogger;
21 import io.github.tonywasher.joceanus.tethys.core.dialog.TethysUICoreFileSelector;
22
23 import javax.swing.JFileChooser;
24 import javax.swing.filechooser.FileNameExtensionFilter;
25 import java.awt.Component;
26 import java.io.File;
27
28
29
30
31 public class TethysUISwingFileSelector
32 extends TethysUICoreFileSelector {
33
34
35
36 private static final OceanusLogger LOGGER = OceanusLogManager.getLogger(TethysUISwingFileSelector.class);
37
38
39
40
41 private final Component theParent;
42
43
44
45
46 private final JFileChooser theChooser;
47
48
49
50
51 private File theSelectedFile;
52
53
54
55
56
57
58 TethysUISwingFileSelector(final Component pParent) {
59 if (pParent == null) {
60 throw new IllegalArgumentException("Cannot create Dialog during initialisation");
61 }
62 theParent = pParent;
63 theChooser = new JFileChooser();
64 theChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
65 }
66
67
68
69
70 public void showDialog() {
71
72 theSelectedFile = null;
73
74
75 theChooser.setDialogTitle(getTitle());
76 theChooser.setCurrentDirectory(getInitialDirectory());
77 final String myName = getInitialFileName();
78 if (myName != null) {
79 final File myFile = new File(theChooser.getCurrentDirectory(), myName);
80 theChooser.setSelectedFile(myFile);
81 }
82
83
84 theChooser.resetChoosableFileFilters();
85 final String myExt = getExtension();
86 if (myExt != null) {
87 theChooser.setFileFilter(new FileNameExtensionFilter("Filter", myExt));
88 }
89
90
91 final int myResult = useSave()
92 ? theChooser.showSaveDialog(theParent)
93 : theChooser.showOpenDialog(theParent);
94
95
96 if (myResult == JFileChooser.APPROVE_OPTION) {
97 theSelectedFile = theChooser.getSelectedFile();
98 }
99 }
100
101 @Override
102 public File selectFile() {
103 TethysUISwingDialog.runInSwingThread(this::showDialog);
104 return theSelectedFile;
105 }
106 }