Custom JFileChooser

The default JFileChooser doesn’t prompt to overwrite files when saving. It also doesn’t automatically add an extension to the file if the user didn’t type one. I had to do a custom one to support these features for better usability.

The limitation of this specific implementation is it only supports one “image” extension, and it’s not i18n-ed. Customize it more for your own needs.

private class CustomFileChooser extends JFileChooser {
  private String extension;
  public CustomFileChooser(String extension) {
    super();
    this.extension = extension;
    addChoosableFileFilter(new FileNameExtensionFilter(
      String.format("%1$s Images (*.%1$s)", extension), extension));
  }

  @Override public File getSelectedFile() {
    File selectedFile = super.getSelectedFile();

    if (selectedFile != null) {
      String name = selectedFile.getName();
      if (!name.contains("."))
        selectedFile = new File(selectedFile.getParentFile(), 
          name + '.' + extension);
    }

    return selectedFile;
  }

  @Override public void approveSelection() {
    if (getDialogType() == SAVE_DIALOG) {
      File selectedFile = getSelectedFile();
      if ((selectedFile != null) && selectedFile.exists()) {
        int response = JOptionPane.showConfirmDialog(this,
          "The file " + selectedFile.getName() + 
          " already exists. Do you want to replace the existing file?",
          "Ovewrite file", JOptionPane.YES_NO_OPTION,
          JOptionPane.WARNING_MESSAGE);
        if (response != JOptionPane.YES_OPTION)
          return;
      }
    }

    super.approveSelection();
  }
}

One thought to “Custom JFileChooser”

Leave a Reply