Reputation: 625
I have to write a Java 8 Swing app and a part of the application generates an output file (Excel spreadsheet). So at some point in the UI, the user will have to:
I'm interested in what a decent UX solution here is, and how that maps to Swing controls and their layout.
I know I can use JFileChooser
to choose a directory or a specific file, but I've never used it to select a directory and enter the name of a new (doesn't exist on the file system yet) file name + extension.
Any ideas as to what solution I can offer here that is functional, elegant and simple/easy to use & understand?
Upvotes: 0
Views: 138
Reputation: 112
You can use Apache's FileNameUtils, or implement you own extension extraction with String manipulation using substring and indexOf... I'll give you an example of first case.
After using a default JFileChooser as suggested, you can just check for specified file name, as JFileChooser will return a File object (or null if nothing is selected, so first check for null values):
JFileChooser fileChooser = new JFileChooser();
File selectedFile = fileChooser.getSelectedFile();
if (selectedFile != null) {
String givenExtension = FilenameUtils.getExtension(selectedFile.getName());
boolean noExtension = "".equals(givenExtension);
boolean xlsx = givenExtension.toLowerCase().contains("xlsx");
boolean xls = givenExtension.toLowerCase().contains("xls");
String newFileName = selectedFile.getName();
if (noExtension) {
newFileName += ".xlsx";
} else if (!xlsx && !xls) {
throw new Exception("Invalid name");
}
}
Remove toLowerCase() if you don't want different cases to be accepted.
This should do what you want ;)
Upvotes: 1