Java Code Examples for javax.swing.JFileChooser#setFileFilter()

The following examples show how to use javax.swing.JFileChooser#setFileFilter() . 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: zxpoly   File: MainForm.java    License: GNU General Public License v3.0 6 votes vote down vote up
private File chooseFileForOpen(final String title, final File initial,
                               final AtomicReference<FileFilter> selectedFilter,
                               final FileFilter... filter) {
  final JFileChooser chooser = new JFileChooser(initial);
  for (final FileFilter f : filter) {
    chooser.addChoosableFileFilter(f);
  }
  chooser.setAcceptAllFileFilterUsed(false);
  chooser.setMultiSelectionEnabled(false);
  chooser.setDialogTitle(title);
  chooser.setFileFilter(filter[0]);
  chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

  final File result;
  if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
    result = chooser.getSelectedFile();
    if (selectedFilter != null) {
      selectedFilter.set(chooser.getFileFilter());
    }
  } else {
    result = null;
  }
  return result;
}
 
Example 2
/**
 * Opens a file by opening a JFileChooser which allows the user to select
 * the file they would like to open.
 *
 * @return true if the file successfully opened, false otherwise.
 */

public boolean open()
{
JFileChooser chooser = new JFileChooser(".");
  	FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG Images", "png");
   chooser.setFileFilter(filter);
   int returnVal = chooser.showOpenDialog(null);
   if(returnVal == JFileChooser.APPROVE_OPTION) {
	try{
		File file = chooser.getSelectedFile();
		image = ImageIO.read(file);
		revertImage = copyImage(image);
	}
	catch(Exception e){
		return false;
	}

	return true;
   }
   else
   {
   	return false;
   }
}
 
Example 3
Source Project: netbeans   File: JFXRunPanel.java    License: Apache License 2.0 6 votes vote down vote up
private void buttonWebPageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonWebPageActionPerformed
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(null);
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setMultiSelectionEnabled(false);
    chooser.setFileFilter(new HtmlFileFilter());
    if (lastHtmlFolder != null) {
        chooser.setSelectedFile(lastHtmlFolder);
    } else { // ???
        // workDir = FileUtil.toFile(project.getProjectDirectory()).getAbsolutePath();
        // chooser.setSelectedFile(new File(workDir));
    }
    chooser.setDialogTitle(NbBundle.getMessage(JFXDeploymentPanel.class, "LBL_Select_HTML_File")); // NOI18N
    if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(this)) {
        File file = FileUtil.normalizeFile(chooser.getSelectedFile());
        textFieldWebPage.setText(file.getAbsolutePath());
        lastHtmlFolder = file.getParentFile();
    }
}
 
Example 4
private void loadFile() {
	JFileChooser fileChooser = new JFileChooser();

	FileNameExtensionFilter filter = new FileNameExtensionFilter("HTML Files (*.htm, *.html)", "htm", "html");
	fileChooser.addChoosableFileFilter(filter);
	fileChooser.addChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
	fileChooser.setFileFilter(filter);

	if (internalBalloon.getBalloonContentPath().isSetLastUsedMode()) {
		fileChooser.setCurrentDirectory(new File(internalBalloon.getBalloonContentPath().getLastUsedPath()));
	} else {
		fileChooser.setCurrentDirectory(new File(internalBalloon.getBalloonContentPath().getStandardPath()));
	}
	int result = fileChooser.showSaveDialog(getTopLevelAncestor());
	if (result == JFileChooser.CANCEL_OPTION) return;
	try {
		String exportString = fileChooser.getSelectedFile().toString();
		browseText.setText(exportString);
		internalBalloon.getBalloonContentPath().setLastUsedPath(fileChooser.getCurrentDirectory().getAbsolutePath());
		internalBalloon.getBalloonContentPath().setPathMode(PathMode.LASTUSED);
	}
	catch (Exception e) {
		//
	}
}
 
Example 5
/**
 * Display a dialog box to open a CGX file
 */
private void OpenCGXDialog() {
	JFileChooser fileChooser = new JFileChooser();
	fileChooser.setCurrentDirectory(new File(Settings.previousCGXDirectory)); // System.getProperty("user.home")));
	fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

	FileFilter cgxFilter = new FileTypeFilter(".cgx", bundle.getString("frmMain.CGXFile")); // "CGX
																							// file");
	fileChooser.addChoosableFileFilter(cgxFilter);
	fileChooser.setFileFilter(cgxFilter);

	int result = fileChooser.showOpenDialog(this);
	if (result == JFileChooser.APPROVE_OPTION) {
		File selectedFile = fileChooser.getSelectedFile();
		LoadCGX(selectedFile.getAbsolutePath());
		Settings.previousCGXDirectory = Utils.GetDirFromFilename(selectedFile.getAbsolutePath());
	}
}
 
Example 6
private void jButton_ExportLegendActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_ExportLegendActionPerformed
    // TODO add your handling code here:
    JFileChooser aDlg = new JFileChooser();
    String[] fileExts = new String[]{"lgs"};
    GenericFileFilter mapFileFilter = new GenericFileFilter(fileExts, "LegendScheme file (*.lgs)");
    aDlg.setFileFilter(mapFileFilter);
    String path = System.getProperty("user.dir");
    aDlg.setCurrentDirectory(new File(path));
    if (JFileChooser.APPROVE_OPTION == aDlg.showSaveDialog(this)) {
        File aFile = aDlg.getSelectedFile();
        String filePath = aFile.getAbsolutePath();
        if (!filePath.substring(filePath.length() - 4).equals(".lgs")) {
            filePath = filePath + ".lgs";
        }
        try {
            _legendScheme.exportToXMLFile(filePath);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(FrmLayerProperty.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
 
Example 7
/**
 * Panel action, update entity
 */
@Override
public void actionPerformed(ActionEvent arg0) {
	JFileChooser chooser = new JFileChooser();
	if(filters.size()==0) return;  // @TODO: fail!
	if(filters.size()==1) chooser.setFileFilter(filters.get(0));
	else {
		Iterator<FileFilter> i = filters.iterator();
		while(i.hasNext()) {
			chooser.addChoosableFileFilter(i.next());
		}
	}
	if(lastPath!=null) chooser.setCurrentDirectory(new File(lastPath));
	int returnVal = chooser.showDialog(ro.getMainFrame(), Translator.get("Select"));
	if(returnVal == JFileChooser.APPROVE_OPTION) {
		String newFilename = chooser.getSelectedFile().getAbsolutePath();
		lastPath = chooser.getSelectedFile().getParent();

		ro.undoableEditHappened(new UndoableEditEvent(this,new ActionChangeString(e, newFilename) ) );
	}
}
 
Example 8
@Override
public void actionPerformed(ActionEvent e) {

    final JFileChooser fileChooser = new JFileChooser();
    fileChooser.setMultiSelectionEnabled(false);
    fileChooser.setFileFilter(new FileNameExtensionFilter("PNG Images", "png"));
    if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
        final File file = fileChooser.getSelectedFile();
        SharedDrawable.exportGlyphTextures(file);
    }
}
 
Example 9
/**
 * Get a JFileChooser filtered for X.509 Certificate files.
 *
 * @param basename default filename (without extension)
 * @return JFileChooser object
 */
public static JFileChooser getX509FileChooser(String basename)
{
	JFileChooser chooser = new JFileChooser();
	FileExtFilter extFilter = new FileExtFilter(X509_EXTS, X509_FILE_DESC);
	chooser.addChoosableFileFilter(extFilter);
	chooser.setFileFilter(extFilter);
	chooser.setSelectedFile(getDefaultFile(basename, X509_EXTS[0]));
	chooser.setFileView(new PortecleFileView());
	return chooser;
}
 
Example 10
Source Project: jadx   File: MainWindow.java    License: Apache License 2.0 5 votes vote down vote up
private void saveProjectAs() {
	JFileChooser fileChooser = new JFileChooser();
	fileChooser.setAcceptAllFileFilterUsed(true);
	String[] exts = { JadxProject.PROJECT_EXTENSION };
	String description = "supported files: " + Arrays.toString(exts).replace('[', '(').replace(']', ')');
	fileChooser.setFileFilter(new FileNameExtensionFilter(description, exts));
	fileChooser.setToolTipText(NLS.str("file.save_project"));
	Path currentDirectory = settings.getLastSaveProjectPath();
	if (currentDirectory != null) {
		fileChooser.setCurrentDirectory(currentDirectory.toFile());
	}
	int ret = fileChooser.showSaveDialog(mainPanel);
	if (ret == JFileChooser.APPROVE_OPTION) {
		settings.setLastSaveProjectPath(fileChooser.getCurrentDirectory().toPath());

		Path path = fileChooser.getSelectedFile().toPath();
		if (!path.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(JadxProject.PROJECT_EXTENSION)) {
			path = path.resolveSibling(path.getFileName() + "." + JadxProject.PROJECT_EXTENSION);
		}

		if (Files.exists(path)) {
			int res = JOptionPane.showConfirmDialog(
					this,
					NLS.str("confirm.save_as_message", path.getFileName()),
					NLS.str("confirm.save_as_title"),
					JOptionPane.YES_NO_OPTION);
			if (res == JOptionPane.NO_OPTION) {
				return;
			}
		}
		project.saveAs(path);
		update();
	}
}
 
Example 11
public static File openDialog(String desc, String... fileFormat) {
    JFileChooser fileChooser = createFileChooser();
    fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
    if (fileFormat != null && fileFormat.length > 0) {
        fileChooser.setFileFilter(new FileNameExtensionFilter(desc, fileFormat));
    }
    int option = fileChooser.showOpenDialog(null);
    if (option == JFileChooser.APPROVE_OPTION) {
        return fileChooser.getSelectedFile();
    }
    return null;
}
 
Example 12
Source Project: trufflesqueak   File: FileChooser.java    License: MIT License 5 votes vote down vote up
public static String run() {
    final JFileChooser squeakImageChooser = new JFileChooser();
    squeakImageChooser.setFileFilter(new SqueakImageFilter());
    squeakImageChooser.setApproveButtonToolTipText("Open selected image with TruffleSqueak");
    final long result = squeakImageChooser.showOpenDialog(null);
    if (result == JFileChooser.APPROVE_OPTION) {
        return squeakImageChooser.getSelectedFile().getAbsolutePath();
    }
    return null;
}
 
Example 13
/**
 * Writes the content of the panel to a PNG image, using Java's ImageIO.
 * 
 * @param e  the event.
 */
@Override
public void actionPerformed(ActionEvent e) {
    JFileChooser fileChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
            Resources.localString("JPG_FILE_FILTER_DESCRIPTION"), "jpg");
    fileChooser.addChoosableFileFilter(filter);
    fileChooser.setFileFilter(filter);

    int option = fileChooser.showSaveDialog(this.panel);
    if (option == JFileChooser.APPROVE_OPTION) {
        String filename = fileChooser.getSelectedFile().getPath();
        if (!filename.endsWith(".jpg")) {
            filename = filename + ".jpg";
        }
        Dimension2D size = this.panel.getSize();
        int w = (int) size.getWidth();
        int h = (int) size.getHeight();
        BufferedImage image = new BufferedImage(w, h, 
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        this.panel.getDrawable().draw(g2, new Rectangle(w, h));
        try {
            ImageIO.write(image, "jpeg", new File(filename));
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
}
 
Example 14
Source Project: cncgcodecontroller   File: JPanelSettings.java    License: MIT License 5 votes vote down vote up
private void jBImportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBImportActionPerformed
    JFileChooser fc = DatabaseV2.getFileChooser();
    fc.setFileFilter(new FileFilter() 
    {
        @Override
        public boolean accept(File f) 
        {
            return f.getName().toLowerCase().endsWith(".ois")||f.isDirectory();
        }

        @Override
        public String getDescription() 
        {
            return "Settings files (*.ois)";
        }
    });
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setMultiSelectionEnabled(false);

    if(fc.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
    {
        return;
    }
    
    if(DatabaseV2.load(fc.getSelectedFile()) == false)
    {
        JOptionPane.showMessageDialog(this, "Cannot import settings!");
    }
    
    fireupdateGUI();
    
}
 
Example 15
private void _saveActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event__saveActionPerformed
  int[] i = _oList.getSelectedRows();
  String[] o = new String[i.length];
  for (int j = 0; j < i.length; j++) {
    o[j] = (String) _oList.getValueAt(i[j], 0);
  }
  JFileChooser fc = new JFileChooser();
  fc.setFileFilter(new FileNameExtensionFilter("R data file", "Rdata"));
  if (R != null) {
    fc.setSelectedFile(new File(R.cat("_", o) + ".Rdata"));
    if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION && fc.getSelectedFile() != null) {
      R.save(fc.getSelectedFile(), o);
    }
  }
}
 
Example 16
Source Project: lsdpatch   File: FontEditor.java    License: MIT License 5 votes vote down vote up
void showSaveDialog() {
    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("LSDj Font", "lsdfnt");
    chooser.setFileFilter(filter);
    String fontName = fontSelector.getSelectedItem().toString();
    chooser.setSelectedFile(new java.io.File(fontName + ".lsdfnt"));
    int returnVal = chooser.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        String filename = chooser.getSelectedFile().toString();
        if (!filename.endsWith("lsdfnt")) {
            filename += ".lsdfnt";
        }
        fontMap.save(filename, fontName);
    }
}
 
Example 17
/**
 * Ask the user for a file using the Swing JFileChooser. On macOS,
 * JFileChooser is poorly implemented, and therefore the AWT FileDialog
 * should be used on macOS.
 */
private static String askSwingFile(java.awt.Frame frame, String message,
        String defaultFile, FileNameExtensionFilter filter, boolean load) {

    // load the directory last visited from the preferences
    String LAST_USED_DIRECTORY = "last_directory";
    Preferences prefs = Preferences.userRoot().node(FileUtils.class.getName());
    String lastDir = prefs.get(LAST_USED_DIRECTORY, new File(".").getAbsolutePath());

    JFileChooser fc = new JFileChooser(lastDir);
    if (filter != null) {
        fc.setFileFilter(filter);
    }
    fc.setDialogTitle(message);
    File selFile;
    // set default file
    try {
        File f = new File(new File(defaultFile).getCanonicalPath());
        fc.setSelectedFile(f);
    } catch (Exception e) {
    }

    int result;
    do {
        if (load) {
            // Show open dialog
            result = fc.showOpenDialog(frame);
        } else {
            // Show save dialog
            result = fc.showSaveDialog(frame);
        }

        if (result != JFileChooser.APPROVE_OPTION) {
            return null;
        }

        selFile = fc.getSelectedFile();
        if (selFile == null) {
            return null;
        }

        // store directory in preferences
        prefs.put(LAST_USED_DIRECTORY, selFile.getParent());

    } while (!load && !askOverwrite(selFile, fc));

    return selFile.getPath();
}
 
Example 18
Source Project: netbeans   File: ResultsManager.java    License: Apache License 2.0 4 votes vote down vote up
SelectedFile selectSnapshotTargetFile(final String defaultName, final boolean heapdump) {
    String targetName;
    FileObject targetDir;

    // 1. let the user choose file or directory
    JFileChooser chooser = new JFileChooser();

    if (exportDir != null) {
        chooser.setCurrentDirectory(exportDir);
    }

    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    chooser.setMultiSelectionEnabled(false);
    chooser.setDialogTitle(Bundle.ResultsManager_SelectFileOrDirDialogCaption());
    chooser.setApproveButtonText(Bundle.ResultsManager_SaveButtonName());
    chooser.setAcceptAllFileFilterUsed(false);
    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().endsWith("." + (heapdump ? HEAPDUMP_EXTENSION : SNAPSHOT_EXTENSION)); //NOI18N
            }

            public String getDescription() {
                if (heapdump) {
                    return Bundle.ResultsManager_ProfilerHeapdumpFileFilter(HEAPDUMP_EXTENSION);
                }
                return Bundle.ResultsManager_ProfilerSnapshotFileFilter(SNAPSHOT_EXTENSION);
            }
        });

    if (chooser.showSaveDialog(WindowManager.getDefault().getMainWindow()) != JFileChooser.APPROVE_OPTION) {
        return null; // cancelled by the user
    }

    // 2. process both cases and extract file name and extension to use
    File file = chooser.getSelectedFile();
    String targetExt = heapdump ? HEAPDUMP_EXTENSION : SNAPSHOT_EXTENSION;

    if (file.isDirectory()) { // save to selected directory under default name
        exportDir = chooser.getCurrentDirectory();
        targetDir = FileUtil.toFileObject(FileUtil.normalizeFile(file));
        targetName = defaultName;
    } else { // save to selected file
        exportDir = chooser.getCurrentDirectory();

        targetDir = FileUtil.toFileObject(FileUtil.normalizeFile(exportDir));

        String fName = file.getName();

        // divide the file name into name and extension
        int idx = fName.lastIndexOf('.'); // NOI18N

        if (idx == -1) { // no extension
            targetName = fName;

            // extension will be used from source file
        } else { // extension exists
            if (heapdump || fName.endsWith("." + targetExt)) { // NOI18N
                targetName = fName.substring(0, idx);
                targetExt = fName.substring(idx + 1);
            } else {
                targetName = fName;
            }
        }
    }

    // 3. return a newly created FileObject
    return new SelectedFile(targetDir, targetName, targetExt);
}
 
Example 19
Source Project: PolyGlot   File: ScrMainMenu.java    License: MIT License 4 votes vote down vote up
/**
 * Export dictionary to excel file
 */
private void exportToExcel() {
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Export Language to Excel");
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel Files", "xls");
    chooser.setFileFilter(filter);
    chooser.setApproveButtonText("Save");
    chooser.setCurrentDirectory(core.getWorkingDirectory());

    String fileName = core.getCurFileName().replaceAll(".pgd", ".xls");
    chooser.setSelectedFile(new File(fileName));

    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        fileName = chooser.getSelectedFile().getAbsolutePath();
    } else {
        return;
    }

    if (!fileName.contains(".xls")) {
        fileName += ".xls";
    }

    if (!new File(fileName).exists()
            || InfoBox.actionConfirmation("Overwrite File?", "File with this name and location already exists. Continue/Overwrite?", this)) {
        try {
            Java8Bridge.exportExcelDict(fileName, core,
                    InfoBox.actionConfirmation("Excel Export",
                            "Export all declensions? (Separates parts of speech into individual tabs)",
                            core.getRootWindow()));

            // only prompt user to open if Desktop supported
            if (Desktop.isDesktopSupported()) {
                if (InfoBox.actionConfirmation("Export Sucess", "Language exported to " + fileName + ".\nOpen now?", this)) {
                    Desktop.getDesktop().open(new File(fileName));
                }
            } else {
                InfoBox.info("Export Status", "Language exported to " + fileName + ".", core.getRootWindow());
            }
        } catch (IOException e) {
            IOHandler.writeErrorLog(e);
            InfoBox.info("Export Problem", e.getLocalizedMessage(), core.getRootWindow());
        }
    }
}
 
Example 20
public void boardLoad() {
    JFileChooser fc = new JFileChooser(loadPath);
    setDialogSize(fc);
    fc.setDialogTitle(Messages.getString("BoardEditor.loadBoard"));
    fc.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File dir) {
            return (dir.getName().endsWith(".board") || dir.isDirectory()); //$NON-NLS-1$
        }

        @Override
        public String getDescription() {
            return "*.board";
        }
    });
    ignoreHotKeys = true;
    int returnVal = fc.showOpenDialog(frame);
    ignoreHotKeys = false;
    saveDialogSize(fc);
    if ((returnVal != JFileChooser.APPROVE_OPTION) || (fc.getSelectedFile() == null)) {
        // I want a file, y'know!
        return;
    }
    curfile = fc.getSelectedFile();
    loadPath = curfile.getPath();
    // load!
    try (InputStream is = new FileInputStream(fc.getSelectedFile())) {            
        // tell the board to load!
        StringBuffer errBuff = new StringBuffer();
        board.load(is, errBuff, true);
        if (errBuff.length() > 0) {
            showBoardValidationReport(errBuff);
        }
        // Board generation in a game always calls BoardUtilities.combine
        // This serves no purpose here, but is necessary to create 
        // flipBGVert/flipBGHoriz lists for the board, which is necessary 
        // for the background image to work in the BoardEditor
        board = BoardUtilities.combine(board.getWidth(), board.getHeight(), 1, 1, 
                new IBoard[]{board}, Collections.singletonList(false), MapSettings.MEDIUM_GROUND);
        game.setBoard(board);
        cheRoadsAutoExit.setSelected(board.getRoadsAutoExit());
        mapSettings.setBoardSize(board.getWidth(), board.getHeight());
        refreshTerrainList();
        setupUiFreshBoard();
    } catch (IOException ex) {
        System.err.println("error opening file to load!"); //$NON-NLS-1$
        System.err.println(ex);
    }
}