Example usage for javax.swing JFileChooser addChoosableFileFilter

List of usage examples for javax.swing JFileChooser addChoosableFileFilter

Introduction

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

Prototype

@BeanProperty(preferred = true, description = "Adds a filter to the list of user choosable file filters.")
public void addChoosableFileFilter(FileFilter filter) 

Source Link

Document

Adds a filter to the list of user choosable file filters.

Usage

From source file:org.fhaes.fhsamplesize.view.FHSampleSize.java

/**
 * Open a JFileChooser and return the file that the user specified for saving. Takes a parameter that specifies the type of file. Either
 * TAB or PNG.//from   www .  j  av  a2 s.  c  o  m
 * 
 * @return
 */
private File getFileFromSaveDialog(String fileTypeToSave) {

    String lastVisitedFolder = App.prefs.getPref(PrefKey.PREF_LAST_EXPORT_FOLDER, null);
    JFileChooser fc = new JFileChooser(lastVisitedFolder);
    File outputFile;

    if (fileTypeToSave == "TAB") {
        TABFilter filterTAB = new TABFilter();
        fc.addChoosableFileFilter(filterTAB);
        fc.setFileFilter(filterTAB);
        fc.setDialogTitle("Export table as text file...");

    } else if (fileTypeToSave == "PDF") {
        PDFFilter filterPDF = new PDFFilter();
        fc.addChoosableFileFilter(filterPDF);
        fc.setFileFilter(filterPDF);
        fc.setDialogTitle("Export chart as PDF...");
    }

    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setMultiSelectionEnabled(false);

    int returnVal = fc.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        outputFile = fc.getSelectedFile();

        if (FileUtils.getExtension(outputFile.getAbsolutePath()) == "") {
            log.debug("Output file extension not set by user");

            if (fc.getFileFilter().getDescription().equals(new CSVFileFilter().getDescription())) {
                log.debug("Adding csv extension to output file name");
                outputFile = new File(outputFile.getAbsolutePath() + ".csv");
            } else if (fc.getFileFilter().getDescription().equals(new PDFFilter().getDescription())) {
                log.debug("Adding pdf extension to output file name");
                outputFile = new File(outputFile.getAbsolutePath() + ".pdf");
            }
        } else {
            log.debug("Output file extension set my user to '"
                    + FileUtils.getExtension(outputFile.getAbsolutePath()) + "'");
        }

        App.prefs.setPref(PrefKey.PREF_LAST_EXPORT_FOLDER, outputFile.getAbsolutePath());
    } else {
        return null;
    }

    if (outputFile.exists()) {
        Object[] options = { "Overwrite", "No", "Cancel" };

        // notes about parameters: null (don't use custom icon), options (the titles of buttons), options[0] (default button title)
        int response = JOptionPane.showOptionDialog(App.mainFrame,
                "The file '" + outputFile.getName() + "' already exists.  Are you sure you want to overwrite?",
                "Confirm", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
                options[0]);

        if (response != JOptionPane.YES_OPTION)
            return null;
    }
    return outputFile;
}

From source file:org.gumtree.vis.awt.CompositePanel.java

/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.// w  w  w .ja va 2 s. c  om
 *
 * @throws IOException if there is an I/O error.
 */
@Override
public void doSaveAs() throws IOException {

    JFileChooser fileChooser = new JFileChooser();
    String currentDirectory = System.getProperty(StaticValues.SYSTEM_SAVE_PATH_LABEL);
    if (currentDirectory != null) {
        File savePath = new File(currentDirectory);
        if (savePath.exists() && savePath.isDirectory()) {
            fileChooser.setCurrentDirectory(savePath);
        }
    }
    ExtensionFileFilter pngFilter = new ExtensionFileFilter("PNG_Image_Files", ".png");
    ExtensionFileFilter jpgFilter = new ExtensionFileFilter("JPG_Image_Files", ".jpg");
    fileChooser.addChoosableFileFilter(pngFilter);
    fileChooser.addChoosableFileFilter(jpgFilter);

    int option = fileChooser.showSaveDialog(this);
    if (option == JFileChooser.APPROVE_OPTION) {
        String filename = fileChooser.getSelectedFile().getPath();
        String selectedDescription = fileChooser.getFileFilter().getDescription();
        String fileExtension = StaticValues.DEFAULT_IMAGE_FILE_EXTENSION;
        if (selectedDescription.toLowerCase().contains("png")) {
            fileExtension = "png";
            if (!filename.toLowerCase().endsWith(".png")) {
                filename = filename + ".png";
            }
        } else if (selectedDescription.toLowerCase().contains("jpg")) {
            fileExtension = "jpg";
            if (!filename.toLowerCase().endsWith(".jpg")) {
                filename = filename + ".jpg";
            }
        }
        File selectedFile = new File(filename);
        int confirm = JOptionPane.YES_OPTION;
        if (selectedFile.exists()) {
            confirm = JOptionPane.showConfirmDialog(this, selectedFile.getName() + " exists, overwrite?",
                    "Confirm Overwriting", JOptionPane.YES_NO_OPTION);
        }
        if (confirm == JOptionPane.YES_OPTION) {
            saveTo(filename, fileExtension);
            System.setProperty(StaticValues.SYSTEM_SAVE_PATH_LABEL, fileChooser.getSelectedFile().getParent());
        }
    }
}

From source file:org.tsho.dmc2.core.chart.jfree.DmcChartPanel.java

/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.//from w w w  .j  a  v a 2  s.  co m
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {

    JFileChooser fileChooser = new JFileChooser();
    ExtensionFileFilter filter = new ExtensionFileFilter(localizationResources.getString("PNG_Image_Files"),
            ".png");
    fileChooser.addChoosableFileFilter(filter);
    fileChooser.addChoosableFileFilter(new ExtensionFileFilter("All files", ""));

    int option = fileChooser.showSaveDialog(this);
    if (option == JFileChooser.APPROVE_OPTION) {
        String filename = fileChooser.getSelectedFile().getPath();
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }

        OutputStream out = new BufferedOutputStream(new FileOutputStream(new File(filename)));
        PngEncoder encoder = new PngEncoder(chartBuffer, true, 0, 9);
        out.write(encoder.pngEncode());
        out.close();
    }
}

From source file:com.freedomotic.jfrontend.MainWindow.java

/**
 *
 * @param evt/*from   w w  w. j  av  a  2 s . c  o m*/
 */
private void mnuRoomBackgroundActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuRoomBackgroundActionPerformed

    ZoneLogic zone = drawer.getSelectedZone();

    if (zone == null) {
        JOptionPane.showMessageDialog(this, i18n.msg("select_room_first"));
    } else {
        final JFileChooser fc = new JFileChooser(Info.PATHS.PATH_RESOURCES_FOLDER);
        OpenDialogFileFilter filter = new OpenDialogFileFilter();
        filter.addExtension("png");
        filter.addExtension("jpeg");
        filter.addExtension("jpg");
        filter.setDescription("Image files (png, jpeg)");
        fc.addChoosableFileFilter(filter);
        fc.setFileFilter(filter);

        int returnVal = fc.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would open the file.
            LOG.info("Opening room background file \"{}\"", file.getAbsolutePath());
            zone.getPojo().setTexture(file.getName());
            drawer.setNeedRepaint(true);
            frameMap.validate();
        }
    }
}

From source file:lu.fisch.moenagade.model.Project.java

public void openImage(Frame frame) {
    JFileChooser fc = new JFileChooser();
    fc.setSelectedFile(new File(lastOpenedImage));
    fc.setAcceptAllFileFilterUsed(false);
    fc.addChoosableFileFilter(new FileFilter() {
        @Override//from   w ww . j a v  a2 s  .  c o m
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }

            String extension = getExtension(f);
            if (extension != null) {
                if (extension.equals("png") || extension.equals("jpg") || extension.equals("jpeg")) {
                    return true;
                } else {
                    return false;
                }
            }

            return false;
        }

        @Override
        public String getDescription() {
            return "Supported image files (*.jpg, *.png)";
        }
    });
    int returnVal = fc.showDialog(frame, "Add image");
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        loadImage(fc.getSelectedFile());
    }

}

From source file:lu.fisch.moenagade.model.Project.java

public void openSound(Frame frame) {
    JFileChooser fc = new JFileChooser();
    fc.setSelectedFile(new File(lastOpenedSound));
    fc.setAcceptAllFileFilterUsed(false);
    fc.addChoosableFileFilter(new FileFilter() {
        @Override//  www  .  j  ava 2  s  . c  o m
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }

            String extension = getExtension(f);
            if (extension != null) {
                if (extension.equals("wav")) {
                    return true;
                } else {
                    return false;
                }
            }

            return false;
        }

        @Override
        public String getDescription() {
            return "Supported sound files (*.wav)";
        }
    });
    int returnVal = fc.showDialog(frame, "Add sound");
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        loadSound(fc.getSelectedFile());
    }

}

From source file:com.freedomotic.jfrontend.MainWindow.java

private void mnuBackgroundActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuBackgroundActionPerformed

    final JFileChooser fc = new JFileChooser(Info.PATHS.PATH_DATA_FOLDER + File.separator + "resources"
            + File.separator + "system" + File.separator + "map" + File.separator);
    OpenDialogFileFilter filter = new OpenDialogFileFilter();
    filter.addExtension("png");
    filter.addExtension("jpeg");
    filter.addExtension("jpg");
    filter.setDescription("Image files (png, jpeg)");
    fc.addChoosableFileFilter(filter);
    fc.setFileFilter(filter);//from   w w w  .j  a va 2  s  . co m

    int returnVal = fc.showOpenDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        //This is where a real application would open the file.
        LOG.info("Opening \"{}\"", file.getAbsolutePath());
        file = this.moveBackgroundFile(file);
        drawer.getCurrEnv().getPojo().setBackgroundImage(file.getAbsolutePath());
        drawer.setNeedRepaint(true);
        frameMap.validate();
    }
}

From source file:com.marginallyclever.makelangelo.MainGUI.java

private void SaveFileDialog() {
    // Note: source for ExampleFileFilter can be found in FileChooserDemo,
    // under the demo/jfc directory in the Java 2 SDK, Standard Edition.
    String s = recentFiles.get(0);
    String filename = (s.length() > 0) ? filename = s : "";

    FileFilter filterGCODE = new FileNameExtensionFilter(translator.get("FileTypeGCode"), "ngc");

    JFileChooser fc = new JFileChooser(new File(filename));
    fc.addChoosableFileFilter(filterGCODE);
    if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        String selectedFile = fc.getSelectedFile().getAbsolutePath();

        if (!selectedFile.toLowerCase().endsWith(".ngc")) {
            selectedFile += ".ngc";
        }/*w  w w.ja  v a  2 s  . co  m*/

        try {
            gcode.Save(selectedFile);
        } catch (IOException e) {
            Log("<span style='color:red'>" + translator.get("Failed") + e.getMessage() + "</span>\n");
            return;
        }
    }
}

From source file:com.marginallyclever.makelangelo.MainGUI.java

public void OpenFileDialog() {
    // Note: source for ExampleFileFilter can be found in FileChooserDemo,
    // under the demo/jfc directory in the Java 2 SDK, Standard Edition.
    String s = recentFiles.get(0);
    String filename = (s.length() > 0) ? filename = s : "";

    FileFilter filterGCODE = new FileNameExtensionFilter(translator.get("FileTypeGCode"), "ngc");
    FileFilter filterImage = new FileNameExtensionFilter(translator.get("FileTypeImage"), "jpg", "jpeg", "png",
            "wbmp", "bmp", "gif");
    FileFilter filterDXF = new FileNameExtensionFilter(translator.get("FileTypeDXF"), "dxf");

    JFileChooser fc = new JFileChooser(new File(filename));
    fc.addChoosableFileFilter(filterImage);
    fc.addChoosableFileFilter(filterDXF);
    fc.addChoosableFileFilter(filterGCODE);
    if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        String selectedFile = fc.getSelectedFile().getAbsolutePath();

        // if machine is not yet calibrated
        if (machineConfiguration.IsPaperConfigured() == false) {
            JOptionPane.showMessageDialog(null, translator.get("SetPaperSize"));
            return;
        }/*from   w w  w.ja va2  s .  com*/
        OpenFileOnDemand(selectedFile);
    }
}

From source file:musite.ui.MusiteResultPanel.java

public boolean saveResult(boolean showConfirm) {
    JFileChooser fc = new JFileChooser(MusiteInit.defaultPath);

    // TODO: windows reserverd
    String fileName = panelName.replaceAll("[" + StringUtil.toOct("|\\?*<\":>+[]/") + "]+", "_");
    fc.setSelectedFile(new File(MusiteInit.defaultPath + File.separator + fileName + ".pred.xml.gz"));

    ArrayList<String> exts = new ArrayList<String>(2);
    exts.add("xml");
    exts.add("xml.gz");
    fc.addChoosableFileFilter(new FileExtensionsFilter(exts, "Prediction XML file (.xml, .xml.gz)"));

    exts = new ArrayList<String>(2);
    exts.add("pred.xml");
    exts.add("pred.xml.gz");
    fc.addChoosableFileFilter(new FileExtensionsFilter(exts, "Prediction result file (pred.xml, pred.xml.gz)"));

    //fc.setAcceptAllFileFilterUsed(true);
    fc.setDialogTitle("Save the the result to...");
    int returnVal = fc.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        MusiteInit.defaultPath = file.getParent();

        String filePath = MusiteInit.defaultPath + File.separator + file.getName();

        //            if (!filePath.toLowerCase().endsWith(".xml")&&!filePath.toLowerCase().endsWith(".xml.gz")) {
        //                filePath += ".pred.xml.gz";
        //            }

        if (IOUtil.fileExist(filePath)) {
            int ret = JOptionPane.showConfirmDialog(this, "Are you sure to replace the existing file?",
                    "Relace the existing file?", JOptionPane.YES_NO_OPTION);
            if (ret == JOptionPane.NO_OPTION)
                return false;
        }//from   ww w.j  a  v a2s.co  m

        PredictionResultXMLWriter writer = PredictionResultXMLWriter.createWriter();
        WriteTask task = new WriteTask(result, writer, filePath);

        TaskUtil.execute(task);
        if (task.success()) {
            if (showConfirm)
                JOptionPane.showMessageDialog(this, "Result saved!");
            saved = true;
            return true;
        } else {
            JOptionPane.showMessageDialog(this, "Failed to save the result.");
            return false;
        }
    } else {
        return false;
    }
}