hotmeatballsoup
hotmeatballsoup

Reputation: 625

Using JFileChooser to allow Swing user to specify output location

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:

  1. Select a directory on their file system, where the Excel file will be written to; and then
  2. Enter the name of the Excel file (if they specify ".xls" or ".xlsx" in the file name, the app will output/write the file in the respective XLS/XLSX output; if they omit the file extension the default will be XLSX)

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

Answers (1)

Alessio Moraschini
Alessio Moraschini

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

Related Questions