Example usage for javax.swing JFileChooser setFileFilter

List of usage examples for javax.swing JFileChooser setFileFilter

Introduction

In this page you can find the example usage for javax.swing JFileChooser setFileFilter.

Prototype

@BeanProperty(preferred = true, description = "Sets the File Filter used to filter out files of type.")
public void setFileFilter(FileFilter filter) 

Source Link

Document

Sets the current file filter.

Usage

From source file:edu.ku.brc.specify.tasks.WorkbenchTask.java

/**
 * Asks for the type of export and the file name.
 * @param props the properties object to be filled in.
 * @return true if everything was asked for and received.
 *///w  w  w .  j a v a  2 s  .  c  o  m
public static boolean getExportInfo(final Properties props, final String defaultFileName) {
    String extension = "";
    //String fileTypeCaption = "";
    if (true) {
        for (ExportFileConfigurationFactory.ExportableType type : ExportFileConfigurationFactory
                .getExportList()) {
            if (type.getMimeType() == ExportFileConfigurationFactory.XLS_MIME_TYPE) {
                props.setProperty("mimetype", type.getMimeType());
                extension = type.getExtension();
                //fileTypeCaption = type.getCaption();
                break;
            }
        }

    } else {
        ChooseFromListDlg<ExportFileConfigurationFactory.ExportableType> dlg = new ChooseFromListDlg<ExportFileConfigurationFactory.ExportableType>(
                (Frame) UIRegistry.get(UIRegistry.FRAME), getResourceString("WB_FILE_FORMAT"), null,
                ChooseFromListDlg.OKCANCELHELP, ExportFileConfigurationFactory.getExportList(),
                "WorkbenchImportCvs");
        dlg.setModal(true);
        UIHelper.centerAndShow(dlg);

        if (!dlg.isCancelled()) {
            props.setProperty("mimetype", dlg.getSelectedObject().getMimeType());

        } else {
            return false;
        }
        extension = dlg.getSelectedObject().getExtension();
        dlg.dispose();
    }

    //        FileDialog fileDialog = new FileDialog((Frame) UIRegistry.get(UIRegistry.FRAME),
    //                                               String.format(getResourceString("CHOOSE_WORKBENCH_EXPORT_FILE"), fileTypeCaption), FileDialog.SAVE);
    //        fileDialog.setDirectory(getDefaultDirPath(EXPORT_FILE_PATH));
    //        UIHelper.centerAndShow(fileDialog);
    //        fileDialog.dispose();

    JFileChooser chooser = new JFileChooser(getDefaultDirPath(EXPORT_FILE_PATH));
    chooser.setDialogTitle(getResourceString("CHOOSE_WORKBENCH_EXPORT_FILE"));
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setMultiSelectionEnabled(false);
    chooser.setFileFilter(new UIFileFilter("xls", getResourceString("WB_EXCELFILES")));
    if (defaultFileName != null) {
        chooser.setSelectedFile(
                new File(chooser.getCurrentDirectory().getPath() + File.separator + defaultFileName + ".xls"));
    }

    if (chooser.showSaveDialog(UIRegistry.get(UIRegistry.FRAME)) != JFileChooser.APPROVE_OPTION) {
        UIRegistry.getStatusBar().setText("");
        return false;
    }

    File file = chooser.getSelectedFile();
    if (file == null) {
        UIRegistry.getStatusBar().setText(getResourceString("WB_EXPORT_NOFILENAME"));
        return false;
    }

    String path = chooser.getCurrentDirectory().getPath();
    //String path = FilenameUtils.getPath(file.getPath());
    if (StringUtils.isNotEmpty(path)) {
        AppPreferences localPrefs = AppPreferences.getLocalPrefs();
        localPrefs.put(EXPORT_FILE_PATH, path);
    }

    //        String fileName = fileDialog.getFile();
    String fileName = file.getName();
    //        if (StringUtils.isEmpty(fileName))
    //        {
    //            UIRegistry.getStatusBar().setText(getResourceString("WB_EXPORT_NOFILENAME"));
    //            return false;
    //        }

    if (StringUtils.isEmpty(FilenameUtils.getExtension(fileName))) {
        fileName += (fileName.endsWith(".") ? "" : ".") + extension;
    }

    if (StringUtils.isEmpty(fileName)) {
        return false;
    }

    if (file.exists()) {
        PanelBuilder builder = new PanelBuilder(new FormLayout("p:g", "c:p:g"));
        CellConstraints cc = new CellConstraints();

        String msg = String.format("<html><p>%s<br><br>%s<br></p></html>", getResourceString("WB_FILE_EXISTS"),
                getResourceString("WB_OK_TO_OVERWRITE"));
        builder.add(createLabel(msg), cc.xy(1, 1));
        builder.setDefaultDialogBorder();

        CustomDialog confirmer = new CustomDialog((Frame) UIRegistry.get(UIRegistry.FRAME),
                getResourceString("WB_FILE_EXISTS_TITLE"), true, CustomDialog.OKCANCEL, builder.getPanel(),
                CustomDialog.CANCEL_BTN);
        UIHelper.centerAndShow(confirmer);
        confirmer.dispose();
        if (confirmer.isCancelled()) {
            return false;
        }
    }
    props.setProperty("fileName", path + File.separator + fileName);
    return true;
}

From source file:com.nikonhacker.gui.EmulatorUI.java

private void loadState() {
    if (framework.isEmulatorPlaying(Constants.CHIP_TX) || framework.isEmulatorPlaying(Constants.CHIP_FR)) {
        JOptionPane.showMessageDialog(this, "Could not load while playing", "Error", JOptionPane.ERROR_MESSAGE);
        return;//ww  w.  j  a  va  2  s .com
    }
    final JFileChooser fc = new JFileChooser();

    fc.setDialogTitle("Select source file");
    fc.setCurrentDirectory(new java.io.File("."));

    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    /* TODO add chip name to triggers extension */
    fc.setFileFilter(Format.createFilter(STATE_EXTENSION, "Emulator state (*" + STATE_EXTENSION + ")"));

    if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        File sourceFile = fc.getSelectedFile();
        if (!sourceFile.exists()) {
            JOptionPane.showMessageDialog(this, "Could not find file '" + sourceFile.getAbsolutePath() + "'.",
                    "Error", JOptionPane.ERROR_MESSAGE);
        } else {

            // Problem: some UI components install listeners and links will be lost
            closeAllFrames();
            try {
                final String source = sourceFile.getAbsolutePath();
                setTitle(ApplicationInfo.getNameVersion() + " - Loading...");

                framework = EmulationFramework.load(source, prefs);
                framework.setupCallbacks(getCallbackHandler(0), getCallbackHandler(1));
                framework.getMasterClock().setSyncPlay(prefs.isSyncPlay());
                setTitle(ApplicationInfo.getNameVersion() + " - Loaded " + source);
            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, e.getMessage() + "\nSee console for more info", "Error",
                        JOptionPane.ERROR_MESSAGE);
            }
            // some menu items may get disabled
            updateStates();
        }
    }
}

From source file:com.nikonhacker.gui.EmulatorUI.java

private void saveState() {
    if (framework.isEmulatorPlaying(Constants.CHIP_TX) || framework.isEmulatorPlaying(Constants.CHIP_FR)) {
        JOptionPane.showMessageDialog(this, "Could not save while playing", "Error", JOptionPane.ERROR_MESSAGE);
        return;/*w  w  w . ja v a2 s.  c o m*/
    }
    final JFileChooser fc = new JFileChooser();

    fc.setDialogTitle("Select destination file");
    fc.setCurrentDirectory(new java.io.File("."));

    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    /* TODO add chip name to triggers extension */
    fc.setFileFilter(Format.createFilter(STATE_EXTENSION, "Emulator state (*" + STATE_EXTENSION + ")"));

    if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        File destinationFile = fc.getSelectedFile();
        if (!(destinationFile.getAbsolutePath().toLowerCase().endsWith(STATE_EXTENSION))) {
            destinationFile = new File(destinationFile.getAbsolutePath() + STATE_EXTENSION);
        }
        if (!destinationFile.exists() || JOptionPane.showConfirmDialog(this,
                "Are you sure you want to overwrite " + destinationFile.getName(), "Confirm overwrite",
                JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {

            // spying frames insert IO forwarding pins that should not be saved
            closeAllSpyFrames();
            try {
                EmulationFramework.saveStateToFile(framework, destinationFile.getAbsolutePath());
                JOptionPane.showMessageDialog(this, "State saving complete", "Done",
                        JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "Error saving state file\n" + e.getMessage(), "Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}

From source file:Form.Principal.java

private void jLabel2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel2MouseClicked
    // TODO add your handling code here:
    if (editando == false) {
        File Ruta = new File("Imagenes/Fotos Perfil/");
        JFileChooser Examinar = new JFileChooser();
        FileNameExtensionFilter Filtro = new FileNameExtensionFilter("Image", "png", "jpg");
        Examinar.addChoosableFileFilter(Filtro);
        Examinar.setAcceptAllFileFilterUsed(false);
        Examinar.setFileFilter(Filtro);
        int Estatus = Examinar.showOpenDialog(this);
        if (Estatus == JFileChooser.APPROVE_OPTION) {
            File Origen = Examinar.getSelectedFile();
            String Extension = FilenameUtils.getExtension(Origen.getPath());
            File Copia = new File(Variables.getIdUsuario() + "." + Extension);
            try {
                FileUtils.copyFile(Origen, Copia);
                FileUtils.copyFileToDirectory(Copia, Ruta);
                if (Extension.equals("png")) {
                    File jpg = new File("Imagenes/Fotos Perfil/" + Variables.idUsuario + ".jpg");
                    if (jpg.exists()) {
                        jpg.delete();//from ww w  .ja  v  a 2  s.co  m
                    }
                }
                if (Extension.equals("jpg")) {
                    File png = new File("Imagenes/Fotos Perfil/" + Variables.idUsuario + ".png");
                    if (png.exists()) {
                        png.delete();
                    }
                }
                Copia.delete();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (Estatus == JFileChooser.CANCEL_OPTION) {
            System.out.println("Cancelar");
        }
        PerfilUsuario(Variables.idUsuario);
    }
}

From source file:com.att.aro.diagnostics.GraphPanel.java

/**
 * Implements the saving of the graph snapshot.
 */// ww  w  . j  a v  a 2  s .c om
private void saveAs() throws IOException {

    // Determine save directory
    File saveDir = traceData.getTraceDir();
    if (graphPanelSaveDirectory != null) {
        saveDir = new File(graphPanelSaveDirectory);
    }
    JFileChooser fc = new JFileChooser(saveDir);

    // Set up file types
    String[] fileTypesJPG = new String[2];
    String fileDisplayTypeJPG = rb.getString("fileChooser.contentDisplayType.jpeg");
    fileTypesJPG[0] = rb.getString("fileChooser.contentType.jpeg");
    fileTypesJPG[1] = rb.getString("fileChooser.contentType.jpg");
    FileFilter filterJPG = new ExtensionFileFilter(fileDisplayTypeJPG, fileTypesJPG);

    fc.addChoosableFileFilter(fc.getAcceptAllFileFilter());
    String[] fileTypesPng = new String[1];
    String fileDisplayTypePng = rb.getString("fileChooser.contentDisplayType.png");
    fileTypesPng[0] = rb.getString("fileChooser.contentType.png");
    FileFilter filterPng = new ExtensionFileFilter(fileDisplayTypePng, fileTypesPng);
    fc.addChoosableFileFilter(filterPng);
    fc.setFileFilter(filterJPG);
    File plotImageFile = null;

    boolean bSavedOrCancelled = false;
    while (!bSavedOrCancelled) {
        if (fc.showSaveDialog(this.getTopLevelAncestor()) == JFileChooser.APPROVE_OPTION) {
            String strFile = fc.getSelectedFile().toString();
            String strFileLowerCase = strFile.toLowerCase();
            String fileDesc = fc.getFileFilter().getDescription();
            String fileType = rb.getString("fileChooser.contentType.jpg");
            if ((fileDesc.equalsIgnoreCase(rb.getString("fileChooser.contentDisplayType.png"))
                    || strFileLowerCase
                            .endsWith(rb.getString("fileType.filters.dot") + fileTypesPng[0].toLowerCase()))) {
                fileType = fileTypesPng[0];
            }
            if (strFile.length() > 0) {
                // Save current directory
                graphPanelSaveDirectory = fc.getCurrentDirectory().getPath();

                if ((fileType != null) && (fileType.length() > 0)) {
                    String fileTypeLowerCaseWithDot = rb.getString("fileType.filters.dot")
                            + fileType.toLowerCase();
                    if (!strFileLowerCase.endsWith(fileTypeLowerCaseWithDot)) {
                        strFile += rb.getString("fileType.filters.dot") + fileType;
                    }
                }
                plotImageFile = new File(strFile);
                boolean bAttemptToWriteToFile = true;
                if (plotImageFile.exists()) {
                    if (MessageDialogFactory.showConfirmDialog(this,
                            MessageFormat.format(rb.getString("fileChooser.fileExists"),
                                    plotImageFile.getAbsolutePath()),
                            rb.getString("fileChooser.confirm"),
                            JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
                        bAttemptToWriteToFile = false;
                    }
                }
                if (bAttemptToWriteToFile) {
                    try {
                        if (fileType.equalsIgnoreCase(fileTypesPng[0])) {
                            BufferedImage bufImage = createImage(pane);
                            ImageIO.write(bufImage, "png", plotImageFile);
                        } else {
                            BufferedImage bufImage = createImage(pane);
                            ImageIO.write(bufImage, "jpg", plotImageFile);
                        }
                        bSavedOrCancelled = true;
                    } catch (IOException e) {
                        MessageDialogFactory.showMessageDialog(this,
                                rb.getString("fileChooser.errorWritingToFile" + plotImageFile.toString()));
                    }
                }
            }
        } else {
            bSavedOrCancelled = true;
        }
    }
}

From source file:net.sf.dvstar.transmission.TransmissionView.java

private File getTorrentFile() {
    File file = null;/*from   w  w  w . j a v  a2s.c o m*/
    JFileChooser fcOpenFile = new JFileChooser(lastOpenDir);
    fcOpenFile.setFileFilter(new TorrentFileFilter());
    int returnVal = fcOpenFile.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        file = fcOpenFile.getSelectedFile();
    }

    return file;
}

From source file:net.sf.dvstar.transmission.TransmissionView.java

@Action
public void doTorrentInfo() {

    JFileChooser fcOpenFile = new JFileChooser(lastOpenDir);
    fcOpenFile.setFileFilter(new TorrentFileFilter());

    int returnVal = fcOpenFile.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fcOpenFile.getSelectedFile();
        lastOpenDir = file.getParentFile();

        globalConfigStorage.setProperty("last-open-dir", lastOpenDir.toString());
        globalConfigStorage.saveConfig();

        TorrentMetaInfo dialog = new TorrentMetaInfo(this, true, file);
        dialog.setLocationRelativeTo(this.getFrame());
        TransmissionApp.getApplication().show(dialog);

    }/* w  ww  .  ja v a2  s  . c o m*/

}

From source file:com.hexidec.ekit.EkitCore.java

/**
 * Method for obtaining a File for input/output using a JFileChooser dialog
 *//*  w w  w.  java2  s  .com*/
private File getFileFromChooser(String startDir, int dialogType, String[] exts, String desc) {
    JFileChooser jfileDialog = new JFileChooser(startDir);
    jfileDialog.setDialogType(dialogType);
    jfileDialog.setFileFilter(new MutableFilter(exts, desc));
    int optionSelected = JFileChooser.CANCEL_OPTION;
    if (dialogType == JFileChooser.OPEN_DIALOG) {
        optionSelected = jfileDialog.showOpenDialog(this);
    } else if (dialogType == JFileChooser.SAVE_DIALOG) {
        optionSelected = jfileDialog.showSaveDialog(this);
    } else // default to an OPEN_DIALOG
    {
        optionSelected = jfileDialog.showOpenDialog(this);
    }
    if (optionSelected == JFileChooser.APPROVE_OPTION) {
        return jfileDialog.getSelectedFile();
    }
    return (File) null;
}

From source file:de.tor.tribes.ui.windows.DSWorkbenchMainFrame.java

public void doImport() {
    String dir = GlobalOptions.getProperty("screen.dir");
    if (dir == null) {
        dir = ".";
    }//from  w  w  w .  j  a  v a2 s  .  com
    JFileChooser chooser = null;
    try {
        chooser = new JFileChooser(dir);
    } catch (Exception e) {
        JOptionPaneHelper.showErrorBox(this,
                "Konnte Dateiauswahldialog nicht ffnen.\nMglicherweise verwendest du Windows Vista. Ist dies der Fall, beende DS Workbench, klicke mit der rechten Maustaste auf DSWorkbench.exe,\n"
                        + "whle 'Eigenschaften' und deaktiviere dort unter 'Kompatibilitt' den Windows XP Kompatibilittsmodus.",
                "Fehler");
        return;
    }
    chooser.setDialogTitle("Datei auswhlen");

    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {

        @Override
        public boolean accept(File f) {
            return (f != null) && (f.isDirectory() || f.getName().endsWith(".xml"));

        }

        @Override
        public String getDescription() {
            return "*.xml";
        }
    });
    int ret = chooser.showOpenDialog(this);
    if (ret == JFileChooser.APPROVE_OPTION) {
        try {
            File f = chooser.getSelectedFile();
            String file = f.getCanonicalPath();
            if (!file.endsWith(".xml")) {
                file += ".xml";
            }

            File target = new File(file);

            String extension = JOptionPane.showInputDialog(this,
                    "Welche Kennzeichnung sollen importierte Plne und Tags erhalten?\n"
                            + "Lass das Eingabefeld leer oder drcke 'Abbrechen', um sie unverndert zu importieren.",
                    "Kennzeichnung festlegen", JOptionPane.INFORMATION_MESSAGE);
            if (extension != null && extension.length() > 0) {
                logger.debug("Using import extension '" + extension + "'");
            } else {
                logger.debug("Using no import extension");
                extension = null;
            }

            if (target.exists()) {
                //do import
                String message = performImport(target, extension);
                JOptionPaneHelper.showInformationBox(this, message, "Import");
            }

            GlobalOptions.addProperty("screen.dir", target.getParent());
        } catch (Exception e) {
            logger.error("Failed to import data", e);
            JOptionPaneHelper.showErrorBox(this, "Import fehlgeschlagen.", "Import");
        }
    }
}

From source file:course_generator.frmMain.java

/**
 * Display a dialog box to open a GPX file
 */// w  ww .  jav a 2 s  .  co m
private void OpenGPXDialog() {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

    FileFilter gpxFilter = new FileTypeFilter(".gpx", "GPX file");
    fileChooser.addChoosableFileFilter(gpxFilter);
    fileChooser.setFileFilter(gpxFilter);

    int result = fileChooser.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        LoadGPX(selectedFile.getAbsolutePath());
    }
}