javax.swing.filechooser.FileFilter Java Examples

The following examples show how to use javax.swing.filechooser.FileFilter. 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 File: MainFrame.java    From netbeans-mmd-plugin with 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 #2
Source File: ExportUtils.java    From netbeans with 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
Source File: ExcelFileSelectionWizardStep.java    From rapidminer-studio with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 #4
Source File: DOM4JSerializer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 #5
Source File: FitBuilder.java    From osp with 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
Source File: SynthFileChooserUIImpl.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
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
Source File: SynthFileChooserUIImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
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
Source File: DirectoryEvent.java    From nordpos with 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 #9
Source File: SynthFileChooserUIImpl.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
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
Source File: SynthFileChooserUIImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
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 File: LocationCustomizer.java    From netbeans with 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 File: GUIFramework.java    From ramus with 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 File: DialogProviderManager.java    From netbeans-mmd-plugin with 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 File: FileChooserDemo.java    From jdk8u_jdk with 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
Source File: FileChooserBuilderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testAddFileFilter() {
    FileChooserBuilder instance = new FileChooserBuilder("j");
    FF one = new FF ("a");
    FF two = new FF ("b");
    instance.addFileFilter(one);
    instance.addFileFilter(two);
    JFileChooser ch = instance.createFileChooser();
    Set<FileFilter> ff = new HashSet<FileFilter>(Arrays.asList(one, two));
    Set<FileFilter> actual = new HashSet<FileFilter>(Arrays.asList(ch.getChoosableFileFilters()));
    assertTrue (actual.containsAll(ff));
    //actual should also contain JFileChooser.getAcceptAllFileFilter()
    assertEquals (ff.size() + 1, actual.size());
}
 
Example #16
Source File: Openfile.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
private boolean openSnapshot(final File file, final List<SnapshotCategory> snapshots) {
    if (file.isFile()) {
        for (SnapshotCategory s : snapshots) {
            FileFilter filter = s.getFileFilter();

            if (filter.accept(file)) {
                s.openSnapshot(file);
                return true;
            }
        }
    }
    return false;
}
 
Example #17
Source File: SynthFileChooserUIImpl.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
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 #18
Source File: Application.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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 #19
Source File: DeNovoImportDialog.java    From PDV with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Import spectrum file
 * @param evt mouse click event
 */
private void browseSpectraJButtonActionPerformed(ActionEvent evt) {
    JFileChooser fileChooser = new JFileChooser(lastSelectedFolder);
    fileChooser.setDialogTitle("Select Spectrum File");
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileChooser.setMultiSelectionEnabled(true);

    FileFilter filter = new FileFilter() {
        @Override
        public boolean accept(File myFile) {

            return myFile.getName().toLowerCase().endsWith(".mgf")
                    || myFile.getName().toLowerCase().endsWith(".dup")
                    || myFile.isDirectory();
        }

        @Override
        public String getDescription() {
            return " Mascot Generic Format (.mgf)";
        }
    };

    fileChooser.setFileFilter(filter);

    int returnValue = fileChooser.showDialog(this, "OK");

    if (returnValue == JFileChooser.APPROVE_OPTION) {
        File[] selectedFiles = fileChooser.getSelectedFiles();
        for (File selectedFile : selectedFiles) {
            if (selectedFile.exists()) {
                spectrumFile = selectedFile;
                lastSelectedFolder = selectedFile.getParent();
            }

        }
        spectrumFileJTextField.setText(spectrumFile.getName() + " selected.");
        validateInput();
    }
}
 
Example #20
Source File: SwingExportInteraction.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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 fileFilter) {
    JFileChooser chooser = new JFileChooser();
    chooser.addChoosableFileFilter(fileFilter);

    if (chooser.showSaveDialog(parent) != JFileChooser.APPROVE_OPTION) {
        return null;
    }

    return chooser.getSelectedFile();
}
 
Example #21
Source File: JFileChooserOperator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Maps {@code JFileChooser.getChoosableFileFilters()} through queue
 */
public FileFilter[] getChoosableFileFilters() {
    return ((FileFilter[]) runMapping(new MapAction<Object>("getChoosableFileFilters") {
        @Override
        public Object map() {
            return ((JFileChooser) getSource()).getChoosableFileFilters();
        }
    }));
}
 
Example #22
Source File: FileChooserDemo.java    From jdk8u-dev-jdk with 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 #23
Source File: FileChooserDemo.java    From hottub with 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 #24
Source File: FileChooserAdapter.java    From weblaf with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void fileFilterChanged ( final FileFilter oldFilter, final FileFilter newFilter )
{
    /**
     * Do nothing by default.
     */
}
 
Example #25
Source File: FileChooserBuilder.java    From netbeans with 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 #26
Source File: SynthFileChooserUIImpl.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
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 #27
Source File: SwingImportInteraction.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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 fileFilter) {
    JFileChooser chooser = new JFileChooser();
    chooser.addChoosableFileFilter(fileFilter);

    if (chooser.showOpenDialog(parent) != JFileChooser.APPROVE_OPTION) {
        return null;
    }

    return chooser.getSelectedFile();
}
 
Example #28
Source File: FileChooserDemo.java    From TencentKona-8 with 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 #29
Source File: ExcelPlugin.java    From ramus with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void actionPerformed(ActionEvent e) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(new FileFilter() {

        @Override
        public boolean accept(File f) {
            if (f.isFile()) {
                return f.getName().toLowerCase().endsWith(".xls");
            }
            return true;
        }

        @Override
        public String getDescription() {
            return "*.xls";
        }

    });
    int r = chooser.showOpenDialog(framework.getMainFrame());
    if (r == JFileChooser.APPROVE_OPTION) {
        Importer importer = new Importer(framework, tableView
                .getComponent().getRowSet(), ExcelPlugin.this);
        try {
            importer.importFromFile(chooser.getSelectedFile());
        } catch (IOException e1) {
            e1.printStackTrace();
            JOptionPane.showMessageDialog(framework.getMainFrame(), e1
                    .getLocalizedMessage());
        }
    }
}
 
Example #30
Source File: SynthFileChooserUIImpl.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
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;
    }
}