Java Code Examples for java.awt.FileDialog#setFilenameFilter()

The following examples show how to use java.awt.FileDialog#setFilenameFilter() . 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: ImageQuantizationDemo.java    From pumpernickel with MIT License 6 votes vote down vote up
/**
 * If invoked from within a Frame: this pulls up a FileDialog to browse for
 * a file. If this is invoked from a secure applet: then this will throw an
 * exception.
 * 
 * @param ext
 *            an optional list of extensions
 * @return a File, or null if the user declined to select anything.
 */
public File browseForFile(String... ext) {
	Window w = SwingUtilities.getWindowAncestor(this);
	if (!(w instanceof Frame))
		throw new IllegalStateException();
	Frame frame = (Frame) w;
	FileDialog fd = new FileDialog(frame);
	if (ext != null && ext.length > 0
			&& (!(ext.length == 1 && ext[0] == null)))
		fd.setFilenameFilter(new SuffixFilenameFilter(ext));
	fd.pack();
	fd.setLocationRelativeTo(null);
	fd.setVisible(true);
	String d = fd.getFile();
	if (d == null)
		return null;
	return new File(fd.getDirectory() + fd.getFile());
}
 
Example 2
Source File: FileUtils.java    From toxiclibs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Displays a standard AWT file dialog for choosing a file for loading or
 * saving.
 * 
 * @param frame
 *            parent frame
 * @param title
 *            dialog title
 * @param path
 *            base directory (or null)
 * @param filter
 *            a FilenameFilter implementation (or null)
 * @param mode
 *            either FileUtils.LOAD or FileUtils.SAVE
 * @return path to chosen file or null, if user has canceled
 */
public static String showFileDialog(final Frame frame, final String title,
        String path, FilenameFilter filter, final int mode) {
    String fileID = null;
    FileDialog fd = new FileDialog(frame, title, mode);
    if (path != null) {
        fd.setDirectory(path);
    }
    if (filter != null) {
        fd.setFilenameFilter(filter);
    }
    fd.setVisible(true);
    if (fd.getFile() != null) {
        fileID = fd.getFile();
        fileID = fd.getDirectory() + fileID;
    }
    return fileID;
}
 
Example 3
Source File: SaveGameFileChooser.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Displays a file chooser dialog for the user to select the file to which the current game should
 * be saved.
 *
 * @param frame The owner of the file chooser dialog; may be {@code null}.
 * @return The file to which the current game should be saved or {@code null} if the user
 *     cancelled the operation.
 */
public static File getSaveGameLocation(final Frame frame, final GameData gameData) {
  final FileDialog fileDialog = new FileDialog(frame);
  fileDialog.setMode(FileDialog.SAVE);
  fileDialog.setDirectory(ClientSetting.saveGamesFolderPath.getValueOrThrow().toString());
  fileDialog.setFilenameFilter((dir, name) -> GameDataFileUtils.isCandidateFileName(name));
  fileDialog.setFile(getSaveGameName(gameData));

  fileDialog.setVisible(true);
  final String fileName = fileDialog.getFile();
  if (fileName == null) {
    return null;
  }

  // If the user selects a filename that already exists,
  // the AWT Dialog will ask the user for confirmation
  return new File(fileDialog.getDirectory(), GameDataFileUtils.addExtensionIfAbsent(fileName));
}
 
Example 4
Source File: MainFrame.java    From mpcmaid with GNU Lesser General Public License v2.1 6 votes vote down vote up
public void open() {
	final FileDialog openDialog = new FileDialog(this);
	openDialog.setDirectory(Preferences.getInstance().getOpenPath());
	openDialog.setMode(FileDialog.LOAD);
	openDialog.setFilenameFilter(new FilenameFilter() {
		public boolean accept(File dir, String name) {
			String[] supportedFiles = { "PGM", "pgm" };
			for (int i = 0; i < supportedFiles.length; i++) {
				if (name.endsWith(supportedFiles[i])) {
					return true;
				}
			}
			return false;
		}
	});
	openDialog.setVisible(true);
	Preferences.getInstance().setOpenPath(openDialog.getDirectory());
	if (openDialog.getDirectory() != null && openDialog.getFile() != null) {
		String filePath = openDialog.getDirectory() + openDialog.getFile();
		System.out.println(filePath);
		final File pgmFile = new File(filePath);
		final MainFrame newFrame = new MainFrame(pgmFile);
		newFrame.show();
	}
}
 
Example 5
Source File: FileChooser.java    From CQL with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 *
 *
 * @param title
 * @param mode
 * @param filter
 *
 * @return
 */
private static File chooseFileAWT(String title, Mode mode, FileFilter filter) {
	Easik e = Easik.getInstance();
	EasikSettings s = e.getSettings();
	FileDialog dialog = new FileDialog(e.getFrame(), title,
			(mode == Mode.SAVE) ? FileDialog.SAVE : FileDialog.LOAD);

	dialog.setDirectory(s.getDefaultFolder());

	if ((mode == Mode.DIRECTORY) && EasikConstants.RUNNING_ON_MAC) {
		System.setProperty("apple.awt.fileDialogForDirectories", "true");
	} else if (filter != null) {
		dialog.setFilenameFilter(filter);
	}

	// Show the dialog (this blocks until the user is done)
	dialog.setVisible(true);

	if ((mode == Mode.DIRECTORY) && EasikConstants.RUNNING_ON_MAC) {
		System.setProperty("apple.awt.fileDialogForDirectories", "false");
	}

	String filename = dialog.getFile();

	if (filename == null) {
		return null;
	}

	File selected = new File(dialog.getDirectory(), filename);

	if (mode != Mode.DIRECTORY) {
		s.setProperty("folder_last", selected.getParentFile().getAbsolutePath());
	}

	return selected;
}
 
Example 6
Source File: FileDialogUtils.java    From pumpernickel with MIT License 5 votes vote down vote up
/**
 * Returns files the user selected or an empty array if the user cancelled
 * the dialog.
 */
public static File[] showOpenDialog(Frame f, String title,
		boolean allowMultipleSelection, FilenameFilter filter) {
	FileDialog fd = new FileDialog(f, title);
	fd.setMode(FileDialog.LOAD);
	if (filter != null)
		fd.setFilenameFilter(filter);
	fd.pack();
	fd.setMultipleMode(allowMultipleSelection);
	fd.setLocationRelativeTo(null);
	fd.setVisible(true);
	if (fd.getFile() == null)
		return new File[] {};
	return fd.getFiles();
}
 
Example 7
Source File: FileDialogUtils.java    From pumpernickel with MIT License 5 votes vote down vote up
/**
 * Show a save FileDialog.
 * 
 * @param f
 *            the frame that owns the FileDialog.
 * @param title
 *            the dialog title
 * @param filename
 *            the optional default filename shown in the file dialog.
 * @param extension
 *            the file extension ("xml", "png", etc.)
 * @return a File the user chose.
 */
public static File showSaveDialog(Frame f, String title, String filename,
		String extension) {
	if (extension.startsWith("."))
		extension = extension.substring(1);

	FileDialog fd = new FileDialog(f, title);
	fd.setMode(FileDialog.SAVE);
	if (filename != null)
		fd.setFile(filename);
	fd.setFilenameFilter(new SuffixFilenameFilter(extension));
	fd.pack();
	fd.setLocationRelativeTo(null);
	fd.setVisible(true);

	String s = fd.getFile();
	if (s == null)
		return null;

	if (s.toLowerCase().endsWith("." + extension)) {
		return new File(fd.getDirectory() + s);
	}

	// TODO: show a 'are you sure you want to replace' dialog here, if we
	// change the filename
	// native FileDialogs don't always show the right warning dialog IF the
	// file extension
	// isn't present

	return new File(fd.getDirectory() + fd.getFile() + "." + extension);
}
 
Example 8
Source File: FilePanel.java    From pumpernickel with MIT License 5 votes vote down vote up
/**
 * Show a browse dialog, using the current file extensions if they are
 * defined.
 * <p>
 * In a JNLP session this uses a FileOpenService, but otherwise this uses an
 * AWT file dialog.
 *
 * @param component
 *            a component that relates to the Frame the possible dialog may
 *            be anchored to. This can be any component that is showing.
 * @param extensions
 *            a list of possible extensions (or null if all files are
 *            accepted).
 * @return the FileData the user selected, or null if the user cancelled
 *         this operation.
 */
public static FileData doBrowse(Component component, String[] extensions) {
	/*
	 * if(JVM.isJNLP()) { try { FileOpenService fos =
	 * (FileOpenService)ServiceManager.lookup("javax.jnlp.FileOpenService");
	 * final FileContents contents = fos.openFileDialog(null, extensions);
	 * if(contents==null) return null; return new
	 * FileContentsWrapper(contents); } catch(Exception e) {
	 * e.printStackTrace(); } }
	 */
	Window w = SwingUtilities.getWindowAncestor(component);
	if (w instanceof Frame) {
		Frame f = (Frame) w;
		FileDialog fd = new FileDialog(f);
		String[] ext = extensions;
		if (ext != null && ext.length > 0) {
			fd.setFilenameFilter(new SuffixFilenameFilter(ext));
		}
		fd.pack();
		fd.setLocationRelativeTo(null);
		fd.setVisible(true);

		if (fd.getFile() == null)
			return null;

		File file = new File(fd.getDirectory() + fd.getFile());
		return new FileWrapper(file);
	} else {
		throw new RuntimeException("window ancestor: " + w);
	}
}
 
Example 9
Source File: CustomSettingsDialog.java    From swingsane with Apache License 2.0 5 votes vote down vote up
private File getLoadFile(String filename, String extension) {
  FileDialog fd = new FileDialog((JDialog) getRootPane().getTopLevelAncestor(),
      Localizer.localize("LoadScannerOptionsFromFileTitle"), FileDialog.LOAD);
  fd.setDirectory(".");
  FilenameExtensionFilter filter = new FilenameExtensionFilter();
  filter.addExtension("xml");
  fd.setFilenameFilter(filter);
  fd.setModal(true);
  fd.setVisible(true);
  if (fd.getFile() == null) {
    return null;
  }
  return new File(fd.getDirectory() + File.separator + fd.getFile());
}
 
Example 10
Source File: CustomSettingsDialog.java    From swingsane with Apache License 2.0 5 votes vote down vote up
private File getSaveFile(String filename, String extension) {
  FileDialog fd = new FileDialog((JDialog) getRootPane().getTopLevelAncestor(),
      Localizer.localize("SaveScannerOptionsToFileTitle"), FileDialog.SAVE);
  fd.setDirectory(".");
  FilenameExtensionFilter filter = new FilenameExtensionFilter();
  filter.addExtension("xml");
  fd.setFilenameFilter(filter);
  fd.setFile(filename + "." + extension);
  fd.setModal(true);
  fd.setVisible(true);
  if (fd.getFile() == null) {
    return null;
  }
  return new File(fd.getDirectory() + File.separator + fd.getFile());
}
 
Example 11
Source File: PreviewPanel.java    From swingsane with Apache License 2.0 5 votes vote down vote up
private File getSaveFile(String filename, String extension) {
  FileDialog fd = new FileDialog((Frame) getRootPane().getTopLevelAncestor(),
      Localizer.localize("SaveImagesToFileTittle"), FileDialog.SAVE);
  fd.setDirectory(".");
  FilenameExtensionFilter filter = new FilenameExtensionFilter();
  filter.addExtension(extension);
  fd.setFilenameFilter(filter);
  fd.setFile(filename + "." + extension);
  fd.setModal(true);
  fd.setVisible(true);
  return new File(fd.getDirectory() + File.separator + fd.getFile());
}
 
Example 12
Source File: CFileChooser.java    From binnavi with Apache License 2.0 5 votes vote down vote up
private static int showNativeFileDialog(final JFileChooser chooser) {
  final FileDialog result = new FileDialog((Frame) chooser.getParent());

  result.setDirectory(chooser.getCurrentDirectory().getPath());

  final File selected = chooser.getSelectedFile();
  result.setFile(selected == null ? "" : selected.getPath());
  result.setFilenameFilter(new FilenameFilter() {
    @Override
    public boolean accept(final File dir, final String name) {
      return chooser.getFileFilter().accept(new File(dir.getPath() + File.pathSeparator + name));
    }
  });

  if (chooser.getDialogType() == SAVE_DIALOG) {
    result.setMode(FileDialog.SAVE);
  } else {
    // The native dialog only support Open and Save
    result.setMode(FileDialog.LOAD);
  }

  if (chooser.getFileSelectionMode() == DIRECTORIES_ONLY) {
    System.setProperty("apple.awt.fileDialogForDirectories", "true");
  }

  // Display dialog
  result.setVisible(true);

  System.setProperty("apple.awt.fileDialogForDirectories", "false");
  if (result.getFile() == null) {
    return CANCEL_OPTION;
  }

  final String selectedDir = result.getDirectory();
  chooser
      .setSelectedFile(new File(FileUtils.ensureTrailingSlash(selectedDir) + result.getFile()));
  return APPROVE_OPTION;
}
 
Example 13
Source File: FileUtils.java    From toxiclibs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Displays a standard AWT file dialog for choosing a file for loading or
 * saving.
 * 
 * @param frame
 *            parent frame
 * @param title
 *            dialog title
 * @param path
 *            base directory (or null)
 * @param formats
 *            an array of allowed file extensions (or null to allow all)
 * @param mode
 *            either FileUtils.LOAD or FileUtils.SAVE
 * @return path to chosen file or null, if user has canceled
 */
public static String showFileDialog(final Frame frame, final String title,
        String path, final String[] formats, final int mode) {
    String fileID = null;
    FileDialog fd = new FileDialog(frame, title, mode);
    if (path != null) {
        fd.setDirectory(path);
    }
    if (formats != null) {
        fd.setFilenameFilter(new FilenameFilter() {

            public boolean accept(File dir, String name) {
                boolean isAccepted = false;
                for (String ext : formats) {
                    if (name.indexOf(ext) != -1) {
                        isAccepted = true;
                        break;
                    }
                }
                return isAccepted;
            }
        });
    }
    fd.setVisible(true);
    if (fd.getFile() != null) {
        fileID = fd.getFile();
        fileID = fd.getDirectory() + fileID;
    }
    return fileID;
}
 
Example 14
Source File: GameFileSelector.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Opens up a UI pop-up allowing user to select a game file. Returns nothing if user closes the
 * pop-up.
 */
public Optional<File> selectGameFile(final Frame owner) {
  final FileDialog fileDialog = new FileDialog(owner);
  fileDialog.setMode(FileDialog.LOAD);
  fileDialog.setDirectory(ClientSetting.saveGamesFolderPath.getValueOrThrow().toString());
  fileDialog.setFilenameFilter((dir, name) -> GameDataFileUtils.isCandidateFileName(name));
  fileDialog.setVisible(true);

  // FileDialog.getFiles() always returns an array
  // of 1 or 0 items, because FileDialog.multipleMode is false by default
  return Arrays.stream(fileDialog.getFiles()).findAny().map(this::mapFileResult);
}
 
Example 15
Source File: MainFrame.java    From mpcmaid with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void saveAs() {
	final FileDialog saveDialog = new FileDialog(this);
	saveDialog.setDirectory(Preferences.getInstance().getSavePath());
	saveDialog.setMode(FileDialog.SAVE);
	saveDialog.setFilenameFilter(new FilenameFilter() {
		public boolean accept(File dir, String name) {
			String[] supportedFiles = { "PGM", "pgm" };
			for (int i = 0; i < supportedFiles.length; i++) {
				if (name.endsWith(supportedFiles[i])) {
					return true;
				}
			}
			return false;
		}
	});
	saveDialog.setVisible(true);
	Preferences.getInstance().setSavePath(saveDialog.getDirectory());
	String filename = saveDialog.getFile();
	if (saveDialog.getDirectory() != null && filename != null) {
		if (!filename.toUpperCase().endsWith(".PGM")) {
			filename += ".PGM";
		}
		String filePath = saveDialog.getDirectory() + filename;
		System.out.println(filePath);
		final File file = new File(filePath);
		setPgmFile(file);
		program.save(pgmFile);
	}
}
 
Example 16
Source File: Export.java    From BART with MIT License 5 votes vote down vote up
private File chooseFile() {
    JFrame mainFrame = (JFrame) WindowManager.getDefault().getMainWindow();
    FileDialog fileDialog = new FileDialog(mainFrame, new File(System.getProperty("user.home")).toString());
    fileDialog.setTitle("Export changes in cvs file");
    fileDialog.setFile("expected.csv");
    fileDialog.setMode(FileDialog.SAVE);
    fileDialog.setFilenameFilter(new ExtFileFilter("csv"));
    fileDialog.setVisible(true);
    String filename = fileDialog.getFile();
    if (filename == null){
        return null;
    }
    String dir = fileDialog.getDirectory();
    return new File(dir + File.separator + filename);
}