Java Code Examples for javax.swing.filechooser.FileFilter

The following examples show how to use javax.swing.filechooser.FileFilter. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: nordpos   Source File: DirectoryEvent.java    License: GNU General Public License v3.0 6 votes vote down vote up
/** Creates a new instance of DirectoryChooser */
public DirectoryEvent(JTextComponent TxtField) {
    m_jTxtField = TxtField;
    m_fc = new JFileChooser();
    
    m_fc.resetChoosableFileFilters();
    m_fc.addChoosableFileFilter(new FileFilter() {
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            } else {
                String filename = f.getName();
                return filename.endsWith(".jar")
                    || filename.endsWith(".JAR")
                    || filename.endsWith(".zip")
                    || filename.endsWith(".ZIP");
            }
        }
        public String getDescription() {
            return AppLocal.getIntString("filter.dbdriverlib");
        }
    });
    m_fc.setFileSelectionMode(JFileChooser.FILES_ONLY );
}
 
Example 2
Source Project: netbeans   Source File: ExportUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static void showExportDialog(final JFileChooser fileChooser, final Component parent, final ExportProvider[] providers) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            if (fileChooser.showDialog(parent, BUTTON_EXPORT) != JFileChooser.APPROVE_OPTION) return;

            File targetFile = fileChooser.getSelectedFile();
            FileFilter filter = fileChooser.getFileFilter();

            for (ExportProvider provider : providers) {
                FormatFilter format = provider.getFormatFilter();
                if (filter.equals(format)) {
                    targetFile = checkFileExtension(targetFile, format.getExtension());
                    if (checkFileExists(targetFile)) provider.export(targetFile);
                    else showExportDialog(fileChooser, parent, providers);
                    break;
                }
            }
        }
    });
}
 
Example 3
public static DOM4JSettingsNode readSettingsFile(ImportInteraction importInteraction, FileFilter fileFilter) {
    File file = importInteraction.promptForFile(fileFilter);
    if (file == null) {
        return null;
    }

    if (!file.exists()) {
        importInteraction.reportError("File does not exist: " + file.getAbsolutePath());
        return null;  //we should really sit in a loop until they cancel or give us a valid file.
    }

    try {
        SAXReader reader = new SAXReader();
        Document document = reader.read(file);

        return new DOM4JSettingsNode(document.getRootElement());
    } catch (Throwable t) {
        LOGGER.error("Unable to read file: " + file.getAbsolutePath(), t);
        importInteraction.reportError("Unable to read file: " + file.getAbsolutePath());
        return null;
    }
}
 
Example 4
Source Project: netbeans-mmd-plugin   Source File: MainFrame.java    License: Apache License 2.0 6 votes vote down vote up
private void menuOpenFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuOpenFileActionPerformed
  final File file = DialogProviderManager.getInstance()
          .getDialogProvider()
          .msgOpenFileDialog(null, "open-file", "Open file", null, true, new FileFilter[]{
    MMDEditor.MMD_FILE_FILTER,
    PlantUmlTextEditor.SRC_FILE_FILTER,
    KsTplTextEditor.SRC_FILE_FILTER,
    SourceTextEditor.SRC_FILE_FILTER
  }, "Open");
  if (file != null) {
    if (openFileAsTab(file, -1)) {
      try {
        FileHistoryManager.getInstance().registerOpenedProject(file);
      } catch (IOException ex) {
        LOGGER.error("Can't register last opened file", ex); //NOI18N
      }
    }
  }
}
 
Example 5
Source Project: osp   Source File: FitBuilder.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Loads fit functions from an XML file chosen by the user.
 * 
 * @return the path to the file opened, or null if none
 */
private String loadFits() {
 	if (chooser==null) {
 		chooser = OSPRuntime.getChooser();
     for (FileFilter filter: chooser.getChoosableFileFilters()) {
     	if (filter.getDescription().toLowerCase().indexOf("xml")>-1) { //$NON-NLS-1$
         chooser.setFileFilter(filter);
     		break;
     	}
     }
 	}
   int result = chooser.showOpenDialog(FitBuilder.this);
   if(result==JFileChooser.APPROVE_OPTION) {
     OSPRuntime.chooserDir = chooser.getCurrentDirectory().toString();
     String fileName = chooser.getSelectedFile().getAbsolutePath();
     return loadFits(fileName, false);
   }
   return null;
}
 
Example 6
public Component getListCellRendererComponent(JList<? extends FileFilter> list, FileFilter value, int index,
                                              boolean isSelected, boolean cellHasFocus) {
    Component c = delegate.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

    String text = null;
    if (value != null) {
        text = value.getDescription();
    }

    //this should always be true, since SynthComboBoxUI's SynthComboBoxRenderer
    //extends JLabel
    assert c instanceof JLabel;
    if (text != null) {
        ((JLabel)c).setText(text);
    }
    return c;
}
 
Example 7
public Object getSelectedItem() {
    // Ensure that the current filter is in the list.
    // NOTE: we shouldnt' have to do this, since JFileChooser adds
    // the filter to the choosable filters list when the filter
    // is set. Lets be paranoid just in case someone overrides
    // setFileFilter in JFileChooser.
    FileFilter currentFilter = getFileChooser().getFileFilter();
    boolean found = false;
    if(currentFilter != null) {
        for (FileFilter filter : filters) {
            if (filter == currentFilter) {
                found = true;
            }
        }
        if(found == false) {
            getFileChooser().addChoosableFileFilter(currentFilter);
        }
    }
    return getFileChooser().getFileFilter();
}
 
Example 8
/**
 * There must be a configuration given, but might be empty.
 */
public ExcelFileSelectionWizardStep(AbstractWizard parent, ExcelResultSetConfiguration configuration) {
	super(parent, new FileFilter() {

		@Override
		public boolean accept(File f) {
			return f.isDirectory() || f.getName().endsWith("xls") || f.getName().endsWith("xlsx");
		}

		@Override
		public String getDescription() {
			return "Excel Spreadsheets (.xls, .xlsx)";
		}
	});
	this.configuration = configuration;
}
 
Example 9
public Component getListCellRendererComponent(JList<? extends FileFilter> list, FileFilter value, int index,
                                              boolean isSelected, boolean cellHasFocus) {
    Component c = delegate.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

    String text = null;
    if (value != null) {
        text = value.getDescription();
    }

    //this should always be true, since SynthComboBoxUI's SynthComboBoxRenderer
    //extends JLabel
    assert c instanceof JLabel;
    if (text != null) {
        ((JLabel)c).setText(text);
    }
    return c;
}
 
Example 10
public Object getSelectedItem() {
    // Ensure that the current filter is in the list.
    // NOTE: we shouldnt' have to do this, since JFileChooser adds
    // the filter to the choosable filters list when the filter
    // is set. Lets be paranoid just in case someone overrides
    // setFileFilter in JFileChooser.
    FileFilter currentFilter = getFileChooser().getFileFilter();
    boolean found = false;
    if(currentFilter != null) {
        for (FileFilter filter : filters) {
            if (filter == currentFilter) {
                found = true;
            }
        }
        if(found == false) {
            getFileChooser().addChoosableFileFilter(currentFilter);
        }
    }
    return getFileChooser().getFileFilter();
}
 
Example 11
Source Project: netbeans   Source File: LocationCustomizer.java    License: Apache License 2.0 6 votes vote down vote up
private JFileChooser getFileChooser() {
    if (fileChooser == null) {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setMultiSelectionEnabled(false);
        chooser.setAcceptAllFileFilterUsed(false);
        chooser.setDialogType(JFileChooser.OPEN_DIALOG);
        chooser.setDialogTitle(Bundle.LocationCustomizer_ChooseFileDialogCaption());
        chooser.setFileFilter(new FileFilter() {
                public boolean accept(File f) {
                    return f.isDirectory() || f.getName().toLowerCase().endsWith(".java");
                } // NOI18N

                public String getDescription() {
                    return Bundle.LocationCustomizer_FileDialogFilterName();
                }
            });
        fileChooser = chooser;
    }

    return fileChooser;
}
 
Example 12
Source Project: ramus   Source File: GUIFramework.java    License: GNU General Public License v3.0 6 votes vote down vote up
public File showOpenDialog(String name, final String extension) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(new FileFilter() {

        @Override
        public String getDescription() {
            return "*" + extension;
        }

        @Override
        public boolean accept(File f) {
            return (f.isDirectory()) || (f.getName().endsWith(extension));
        }
    });
    String fn = Options.getString(name);
    if (fn != null)
        chooser.setSelectedFile(new File(fn));
    if (chooser.showOpenDialog(getMainFrame()) == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        Options.setString(name, file.getAbsolutePath());
        return file;
    }
    return null;
}
 
Example 13
Source Project: netbeans-mmd-plugin   Source File: DialogProviderManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public File msgSaveFileDialog(final Component parentComponent, final String id, final String title, final File defaultFolder, final boolean fileOnly, final FileFilter[] fileFilters, final String approveButtonText) {
  final FileChooserBuilder builder = new FileChooserBuilder(id)
          .setTitle(title)
          .setDefaultWorkingDirectory(defaultFolder)
          .setFilesOnly(fileOnly)
          .setApproveText(approveButtonText);

  for (final FileFilter filter : fileFilters) {
    builder.addFileFilter(filter);
  }

  if (fileFilters.length != 0) {
    builder.setFileFilter(fileFilters[0]);
  }

  return builder.showSaveDialog();
}
 
Example 14
Source Project: jdk8u_jdk   Source File: FileChooserDemo.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void resetFileFilters(boolean enableFilters,
        boolean showExtensionInDescription) {
    chooser.resetChoosableFileFilters();
    if (enableFilters) {
        FileFilter jpgFilter = createFileFilter(
                "JPEG Compressed Image Files",
                showExtensionInDescription, "jpg");
        FileFilter gifFilter = createFileFilter("GIF Image Files",
                showExtensionInDescription, "gif");
        FileFilter bothFilter = createFileFilter("JPEG and GIF Image Files",
                showExtensionInDescription, "jpg",
                "gif");
        chooser.addChoosableFileFilter(bothFilter);
        chooser.addChoosableFileFilter(jpgFilter);
        chooser.addChoosableFileFilter(gifFilter);
    }
}
 
Example 15
/**
 * This is called when you should ask the user for a source file to read.
 *
 * @return a file to read or null to cancel.
 */
public File promptForFile(FileFilter fileFilters) {
    File settingsFile = getSettingsFile();
    if (!settingsFile.exists())  //if its not present (first time we've run on this machine), just cancel the read.
    {
        return null;
    }
    return settingsFile;
}
 
Example 16
public FileFilter getElementAt(int index) {
    if(index > getSize() - 1) {
        // This shouldn't happen. Try to recover gracefully.
        return getFileChooser().getFileFilter();
    }
    if(filters != null) {
        return filters[index];
    } else {
        return null;
    }
}
 
Example 17
Source Project: hottub   Source File: FileChooserDemo.java    License: GNU General Public License v2.0 5 votes vote down vote up
private FileFilter createFileFilter(String description,
        boolean showExtensionInDescription, String... extensions) {
    if (showExtensionInDescription) {
        description = createFileNameFilterDescriptionFromExtensions(
                description, extensions);
    }
    return new FileNameExtensionFilter(description, extensions);
}
 
Example 18
Source Project: netbeans   Source File: FileChooserBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private void prepareFileChooser(JFileChooser chooser) {
    chooser.setFileSelectionMode(dirsOnly ? JFileChooser.DIRECTORIES_ONLY
            : filesOnly ? JFileChooser.FILES_ONLY :
            JFileChooser.FILES_AND_DIRECTORIES);
    chooser.setFileHidingEnabled(fileHiding);
    chooser.setControlButtonsAreShown(controlButtonsShown);
    chooser.setAcceptAllFileFilterUsed(useAcceptAllFileFilter);
    if (title != null) {
        chooser.setDialogTitle(title);
    }
    if (approveText != null) {
        chooser.setApproveButtonText(approveText);
    }
    if (badger != null) {
        chooser.setFileView(new CustomFileView(new BadgeIconProvider(badger),
                chooser.getFileSystemView()));
    }
    if (PREVENT_SYMLINK_TRAVERSAL) {
        FileUtil.preventFileChooserSymlinkTraversal(chooser,
                chooser.getCurrentDirectory());
    }
    if (filter != null) {
        chooser.setFileFilter(filter);
    }
    if (aDescription != null) {
        chooser.getAccessibleContext().setAccessibleDescription(aDescription);
    }
    if (!filters.isEmpty()) {
        for (FileFilter f : filters) {
            chooser.addChoosableFileFilter(f);
        }
    }
}
 
Example 19
@Override
public void propertyChange(PropertyChangeEvent e) {
	String prop = e.getPropertyName();
	if (JFileChooser.CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY.equals(prop)) {
		this.filters = (FileFilter[]) e.getNewValue();
		fireContentsChanged(this, -1, -1);
	} else if (JFileChooser.FILE_FILTER_CHANGED_PROPERTY.equals(prop)) {
		fireContentsChanged(this, -1, -1);
	}
}
 
Example 20
/**
 * Maps {@code JFileChooser.removeChoosableFileFilter(FileFilter)}
 * through queue
 */
public boolean removeChoosableFileFilter(final FileFilter fileFilter) {
    return (runMapping(new MapBooleanAction("removeChoosableFileFilter") {
        @Override
        public boolean map() {
            return ((JFileChooser) getSource()).removeChoosableFileFilter(fileFilter);
        }
    }));
}
 
Example 21
private FileFilter getFileFilter(String formatName) {
    Iterator<ProductWriterPlugIn> writerPlugIns = ProductIOPlugInManager.getInstance().getWriterPlugIns(formatName);
    if (writerPlugIns.hasNext()) {
        return writerPlugIns.next().getProductFileFilter();
    }
    return null;
}
 
Example 22
Source Project: opensim-gui   Source File: FileUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Utility to create file filters to browse for files of specified "extension" with "description" desc
 */
public static FileFilter getFileFilter(final String extensions, final String desc) {
    if(extensions==null || desc==null) return null;
    // Parse the list of extensions passed in as (*.xyz, *.abc .de) into an array[]
    Vector<String> extensionList = new Vector<String>(2);
    if (extensions.contains(",")){
        StringTokenizer tokenizer = new StringTokenizer(extensions," ,*()");
        while(tokenizer.hasMoreElements()){
            extensionList.add(tokenizer.nextToken());
        }
    }
    else
        extensionList.add(0, extensions);
    
    // Copy list into an array[] (not necessary but to make a final object to be used by inner class
    // Could be done more efficiently
    final String[] extensionsArray = new String[extensionList.size()];
    for(int i=0; i<extensionsArray.length;i++)
        extensionsArray[i] = extensionList.get(i);
    
    return  new FileFilter() {
        public boolean accept(File f) {
            boolean test = false;
            for(int i=0; i<extensionsArray.length && !test; i++){
                test = f.isDirectory() || f.getName().toLowerCase().endsWith(extensionsArray[i]);
             }
            return test;
        }
        
        public String getDescription() {
            return desc +" ("+extensions+")";
        }
    };
}
 
Example 23
Source Project: wandora   Source File: RegexFileChooser.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static java.io.FileFilter ioFileFilter(final FileFilter ff){
    return new java.io.FileFilter(){
        public boolean accept(File pathname){
            return ff.accept(pathname);
        }
    };
}
 
Example 24
@Override
public ExitCode showSetupDialog(Window parent, boolean valueCheckRequired) {

  JFileChooser chooser = new JFileChooser();

  for (FileFilter filter : filters)
    chooser.addChoosableFileFilter(filter);
  chooser.setFileFilter(filters[0]);

  File currentFile = getParameter(projectFile).getValue();
  if (currentFile != null) {
    File currentDir = currentFile.getParentFile();
    if ((currentDir != null) && (currentDir.exists()))
      chooser.setCurrentDirectory(currentDir);
  }

  chooser.setMultiSelectionEnabled(false);

  int returnVal = chooser.showOpenDialog(parent);
  if (returnVal != JFileChooser.APPROVE_OPTION)
    return ExitCode.CANCEL;

  File selectedFile = chooser.getSelectedFile();

  getParameter(projectFile).setValue(selectedFile);

  return ExitCode.OK;

}
 
Example 25
Source Project: CXTouch   Source File: GUIUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static File[] selectFile(Container container, boolean isMultiSelect,
                                FileFilter initialFilter, FileFilter filters[], boolean isOpen) {
    File[] ret = selectFileByFilter(container, initialFilter, filters, null,
            lastSelectedDir == null ? "" : lastSelectedDir, isMultiSelect, isOpen, false);
    if (ret == null) {
        return null;
    } else {
        return ret;
    }
}
 
Example 26
Source Project: netbeans-mmd-plugin   Source File: SourceTextEditor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean saveDocument() throws IOException {
  boolean result = false;

  final TextFile textFile = this.currentTextFile.get();
  final DialogProvider dialogProvider = DialogProviderManager.getInstance().getDialogProvider();

  if (this.title.isChanged()) {
    if (this.isOverwriteAllowed(textFile)) {
      File file = this.title.getAssociatedFile();
      if (file == null) {
        file = dialogProvider
                .msgSaveFileDialog(Main.getApplicationFrame(), "sources-editor", "Save sources", null, true, new FileFilter[]{getFileFilter()}, "Save");
        if (file == null) {
          return result;
        }
      }

      final String editorText = this.editor.getText();
      final byte[] content = editorText.getBytes(StandardCharsets.UTF_8);
      FileUtils.writeByteArrayToFile(file, content);
      this.currentTextFile.set(new TextFile(file, false, content));

      this.originalText = editorText;
      this.title.setChanged(false);
      this.deleteBackup();
      result = true;
    }
  } else {
    result = true;
  }
  return result;
}
 
Example 27
Source Project: visualvm   Source File: HeapDumpCategory.java    License: GNU General Public License v2.0 5 votes vote down vote up
public FileFilter getFileFilter() {
    return new FileFilter() {
        public boolean accept(File f) {
            return f.isDirectory() || isSnapshot(f);
        }
        public String getDescription() {
            String suff = getSuffix();
            return getName() + (suff != null ? " (*" + suff +", *.*"+ ")" : "");    // NOI18N
        }
    };
}
 
Example 28
private FileFilter createFileFilter(String description,
        boolean showExtensionInDescription, String... extensions) {
    if (showExtensionInDescription) {
        description = createFileNameFilterDescriptionFromExtensions(
                description, extensions);
    }
    return new FileNameExtensionFilter(description, extensions);
}
 
Example 29
Source Project: netbeans-mmd-plugin   Source File: DialogProviderManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public File msgOpenFileDialog(@Nullable final Component parentComponent, @Nonnull String id, @Nonnull String title, @Nullable File defaultFolder, boolean filesOnly, @Nonnull @MustNotContainNull FileFilter[] fileFilters, @Nonnull String approveButtonText) {
  final File folderToUse;
  if (defaultFolder == null) {
    folderToUse = cacheOpenFileThroughDialog.find(null, id);
  } else {
    folderToUse = defaultFolder;
  }

  final JFileChooser fileChooser = new JFileChooser(folderToUse);
  fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
  fileChooser.setDialogTitle(title);
  fileChooser.setApproveButtonText(approveButtonText);
  for (final FileFilter f : fileFilters) {
    fileChooser.addChoosableFileFilter(f);
  }
  if (fileFilters.length != 0) {
    fileChooser.setFileFilter(fileFilters[0]);
  }
  fileChooser.setAcceptAllFileFilterUsed(true);
  fileChooser.setMultiSelectionEnabled(false);

  File result = null;
  if (fileChooser.showDialog(GetUtils.ensureNonNull(
      parentComponent == null ? null : SwingUtilities.windowForComponent(parentComponent),
      Main.getApplicationFrame()),
      approveButtonText) == JFileChooser.APPROVE_OPTION) {
    result = cacheOpenFileThroughDialog.put(id, fileChooser.getSelectedFile());
  }

  return result;
}
 
Example 30
Source Project: Bytecoder   Source File: JFileChooser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Resets the choosable file filter list to its starting state. Normally,
 * this removes all added file filters while leaving the
 * <code>AcceptAll</code> file filter.
 *
 * @see #addChoosableFileFilter
 * @see #getChoosableFileFilters
 * @see #removeChoosableFileFilter
 */
public void resetChoosableFileFilters() {
    FileFilter[] oldValue = getChoosableFileFilters();
    setFileFilter(null);
    filters.removeAllElements();
    if(isAcceptAllFileFilterUsed()) {
       addChoosableFileFilter(getAcceptAllFileFilter());
    }
    firePropertyChange(CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY, oldValue, getChoosableFileFilters());
}