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:com.original.widget.OPicture.java

/**
 * very simple method to select an image file.
 * Please be advised that we will create our own file chooser in the
 * near future. Since in our system, people will be not encouraged to
 * access the physical file./*from w ww  . ja  v  a2s  .  c  o m*/
 *
 * Of course, we need to discuss how to handle this issue.
 * @return
 */

private File chooseImgFile() {
    JFileChooser chooser = new JFileChooser(".");
    FileFilter imgType = new OriExtFileFilter("Image files", new String[] { ".jpg", ".gif", ".jpeg", ".png" });
    chooser.addChoosableFileFilter(imgType);
    chooser.setAcceptAllFileFilterUsed(false);
    chooser.setFileFilter(imgType);
    int status = chooser.showOpenDialog(null);
    if (status == JFileChooser.APPROVE_OPTION) {
        File f = chooser.getSelectedFile();
        return f;
    }
    return null;
}

From source file:com.igormaznitsa.jhexed.swing.editor.ui.dialogs.hexeditors.DialogEditSVGImageValue.java

private void buttonSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveAsActionPerformed
    final JFileChooser dlg = new JFileChooser();
    dlg.addChoosableFileFilter(new FileFilter() {

        @Override/*from   w w  w  .  ja v a 2s  .  c  om*/
        public boolean accept(File f) {
            return f.isDirectory() || f.getName().toLowerCase(Locale.ENGLISH).endsWith(".svg");
        }

        @Override
        public String getDescription() {
            return "SVG files (*.svg)";
        }
    });

    if (dlg.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        File file = dlg.getSelectedFile();

        if (FilenameUtils.getExtension(file.getName()).isEmpty()) {
            file = new File(file.getParentFile(), file.getName() + ".svg");
        }

        if (file.exists() && JOptionPane.showConfirmDialog(this.parent,
                "Overwrite file '" + file.getAbsolutePath() + "\'?", "Overwriting",
                JOptionPane.OK_CANCEL_OPTION) == JOptionPane.CANCEL_OPTION) {
            return;
        }
        try {
            FileUtils.writeByteArrayToFile(file, this.value.getImage().getImageData());
        } catch (IOException ex) {
            Log.error("Can't write image [" + file + ']', ex);
            JOptionPane.showMessageDialog(this, "Can't save the file for error!", "IO Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

}

From source file:table.FrequencyTablePanel.java

public String doSaveAs(File f) throws IOException {
    JFileChooser fileChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF Files", "pdf");
    fileChooser.addChoosableFileFilter(filter);
    fileChooser.setFileFilter(filter);/*from   w  w  w. ja  va  2  s. c om*/
    String filename = "";
    int option = fileChooser.showSaveDialog(this);
    if (option == JFileChooser.APPROVE_OPTION) {
        filename = fileChooser.getSelectedFile().getPath();
        if (!filename.endsWith(".png")) {
            filename = filename + ".png";
        }
        saveTableAsPNG(new File(filename), this.table, getWidth(), getHeight());
    }
    return filename;
}

From source file:de.biomedical_imaging.ij.plot.HistogramPlotter.java

public HistogramPlotter(String title, String xlabel, double[][] data, int numberOfParticles,
        int meanTrackLength, IDatasetCreator datacreator) {

    super(title);
    this.title = title;
    this.xlabel = xlabel;
    this.numberOfParticles = numberOfParticles;
    this.meanTrackLength = meanTrackLength;
    IntervalXYDataset xydataset = datacreator.create(data);
    boolean isbarplot = (datacreator instanceof BarplotDataset);
    txt = new JLabel();
    Font f = new Font("Verdana", Font.PLAIN, 12);
    txt.setFont(f);/*from   w  w w.  j av a 2 s  .c  o  m*/

    JFreeChart chart = createChart(xydataset, isbarplot);

    ChartPanel chartPanel = new ChartPanel(chart);

    txt.setText(formatSettingsString());

    main = new JPanel();
    main.setPreferredSize(new java.awt.Dimension(500, 350));
    main.add(chartPanel);
    main.add(txt);
    setContentPane(main);

    setLayout(new BoxLayout(main, BoxLayout.Y_AXIS));

    pack();
    setVisible(true);

    JMenuItem savebutton = ((JMenuItem) chartPanel.getPopupMenu().getComponent(3));
    chartPanel.getPopupMenu().remove(3); // Remove Save button
    //ActionListener al = savebutton.getActionListeners()[0];
    savebutton = new JMenuItem("Save as png");
    //savebutton.removeActionListener(al);
    savebutton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub

            try {
                JFileChooser saveFile = new JFileChooser();
                saveFile.setAcceptAllFileFilterUsed(false);
                saveFile.addChoosableFileFilter(new FileNameExtensionFilter("Images", "png"));
                int userSelection = saveFile.showSaveDialog(main);
                if (userSelection == JFileChooser.APPROVE_OPTION) {
                    BufferedImage bi = ScreenImage.createImage(main);
                    File fileToSave = saveFile.getSelectedFile();
                    String filename = fileToSave.getName();
                    int i = filename.lastIndexOf('.');
                    String suffix = filename.substring(i + 1);
                    String path = fileToSave.getAbsolutePath();
                    if (!(suffix.equals("png"))) {
                        path += ".png";
                    }
                    ScreenImage.writeImage(bi, path);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                IJ.log("" + e.getMessage());
            }

        }
    });
    chartPanel.getPopupMenu().insert(savebutton, 3);

}

From source file:edu.gcsc.vrl.jfreechart.JFExport.java

/**
 * Show dialog for exporting JFreechart object.
 *//*  ww w  .  j  a v  a 2 s .co m*/
public void openExportDialog(JFreeChart jfreechart) {

    JFileChooser chooser = new JFileChooser();
    String path0;
    File file;

    chooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF Files", "pdf"));
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("JPEG Files", "jpg"));
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("PNG Files", "png"));
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("EPS Files", "eps"));
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("SVG Files", "svg"));

    chooser.setFileFilter(new FileNameExtensionFilter("PDF Files", "pdf"));

    int returnVal = chooser.showSaveDialog(null);
    String fd = chooser.getFileFilter().getDescription();

    // Get selected FileFilter 
    String filter_extension = null;
    if (fd.equals("PNG Files")) {
        filter_extension = "png";
    }
    if (fd.equals("SVG Files")) {
        filter_extension = "svg";
    }
    if (fd.equals("JPEG Files")) {
        filter_extension = "jpg";
    }
    if (fd.equals("PDF Files")) {
        filter_extension = "pdf";
    }
    if (fd.equals("EPS Files")) {
        filter_extension = "eps";
    }

    // Cancel
    if (returnVal == JFileChooser.CANCEL_OPTION) {
        return;
    }

    // OK
    if (returnVal == JFileChooser.APPROVE_OPTION) {

        path0 = chooser.getSelectedFile().getAbsolutePath();
        //System.out.println(path0);
        try {
            file = new File(path0);
            // Get extension (if any)
            String ext = JFUtils.getExtension(file);
            // No extension -> use selected Filter
            if (ext == null) {
                file = new File(path0 + "." + filter_extension);
                ext = filter_extension;
            }

            // File exists - overwrite ?
            if (file.exists()) {
                Object[] options = { "OK", "CANCEL" };
                int answer = JOptionPane.showOptionDialog(null, "File exists - Overwrite ?", "Warning",
                        JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
                if (answer != JOptionPane.YES_OPTION) {
                    return;
                }
                //System.out.println(answer+"");
            }

            // Export file
            export(file, jfreechart);
        } catch (Exception f) {
            // I/O - Error
        }
    }
}

From source file:com.opendoorlogistics.core.utils.ui.FileBrowserPanel.java

private static JButton createBrowseButton(final boolean directoriesOnly, final String browserApproveButtonText,
        final JTextField textField, final FileFilter... fileFilters) {
    JButton browseButton = new JButton("...");
    browseButton.addActionListener(new ActionListener() {

        @Override//w ww . ja  va2  s .  com
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();

            if (textField.getText() != null) {
                File file = new File(textField.getText());

                // if the file doesn't exist but the directory does, get that
                if (!file.exists() && file.getParentFile() != null && file.getParentFile().exists()) {
                    file = file.getParentFile();
                }

                if (!directoriesOnly && file.isFile()) {
                    chooser.setSelectedFile(file);
                }

                if (file.isDirectory() && file.exists()) {
                    chooser.setCurrentDirectory(file);
                }
            }

            if (directoriesOnly) {
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            }

            // add filters and automatically select correct one
            if (fileFilters.length == 1) {
                chooser.setFileFilter(fileFilters[0]);
            } else {
                for (FileFilter filter : fileFilters) {
                    chooser.addChoosableFileFilter(filter);
                    if (filter instanceof FileNameExtensionFilter) {
                        if (matchesFilter((FileNameExtensionFilter) filter, textField.getText())) {
                            chooser.setFileFilter(filter);
                        }
                    }
                }
            }

            if (chooser.showDialog(textField, browserApproveButtonText) == JFileChooser.APPROVE_OPTION) {
                //File selected = processSelectedFile(chooser.getSelectedFile());
                File selected = chooser.getSelectedFile();

                String path = selected.getPath();
                FileFilter filter = chooser.getFileFilter();
                if (filter != null && filter instanceof FileNameExtensionFilter) {

                    boolean found = matchesFilter(((FileNameExtensionFilter) chooser.getFileFilter()), path);

                    if (!found) {
                        String[] exts = ((FileNameExtensionFilter) chooser.getFileFilter()).getExtensions();
                        if (exts.length > 0) {
                            path = FilenameUtils.removeExtension(path);
                            path += "." + exts[0];
                        }
                    }

                }
                textField.setText(path);
            }
        }
    });

    return browseButton;
}

From source file:utilities.GraphViewer.java

public void actionPerformed(ActionEvent e) {
    // Evenement button parcourir
    if (e.getSource() == this.parcourir) {

        JFileChooser fileopen = new JFileChooser();
        FiltreSimple filter = new FiltreSimple("Fichier res", "res");
        fileopen.addChoosableFileFilter(filter);
        int ret = fileopen.showDialog(null, "Open file");
        if (ret == JFileChooser.APPROVE_OPTION) {
            File file = fileopen.getSelectedFile();
            System.out.println(file.getPath());
            this.addSensor(file.getPath());

        }/*from  w  ww .jav  a 2  s.com*/

    } else {

        JCheckBox check;
        for (int i = 0; i < this.sensors.size(); i++) {
            check = sensors.get(i);
            if (e.getSource() == check) {
                if (check.isSelected()) {
                    if (!this.isExist(check)) {
                        String s = check.getText();
                        s = s.substring(1);
                        ajouterFichier(this.db.getPath(check.getText()));
                        sensors1.addLast(check);
                        this.graphe.revalidate();
                    }

                } else {
                    this.removeSerie(check.getText());
                    sensors1.remove(check);
                    this.graphe.revalidate();

                }
                break;
            }
        }

    }

}

From source file:EnhancedFileTester.java

public EnhancedFileTester() {
    JButton jb = new JButton("Open File Viewer");
    add(jb);/*from   w w  w.ja v  a2s .  c o  m*/
    ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser(".");
            FileFilter type1 = new ExtensionFilter("Java source", ".java");
            FileFilter type2 = new ExtensionFilter("Image files",
                    new String[] { ".jpg", ".gif", "jpeg", "xbm" });
            FileFilter type3 = new ExtensionFilter("HTML files", new String[] { ".htm", ".html" });
            chooser.addChoosableFileFilter(type1);
            chooser.addChoosableFileFilter(type2);
            chooser.addChoosableFileFilter(type3);
            chooser.setFileFilter(type2); // Initial filter setting
            FileView view = new IconView();
            chooser.setFileView(view);
            int status = chooser.showOpenDialog(EnhancedFileTester.this);
            if (status == JFileChooser.APPROVE_OPTION) {
                File f = chooser.getSelectedFile();
                System.out.println(f);
            }
        }
    };
    jb.addActionListener(listener);
}

From source file:com.swg.parse.docx.OpenWord.java

@Override
public void actionPerformed(ActionEvent e) {

    JFileChooser fc = new JFileChooser();
    fc.setCurrentDirectory(new File("C:/"));
    fc.setAcceptAllFileFilterUsed(false);
    //this authorize only .docx selection
    fc.addChoosableFileFilter(new DocxFileFilter());
    if (selectedFile != null) {
        fc.setSelectedFile(selectedFile);
    }// w w  w. jav a 2 s  . c  o  m
    int returnVal = fc.showDialog(WindowManager.getDefault().getMainWindow(), "Extract Data");

    if (returnVal == JFileChooser.APPROVE_OPTION) {

        File file = fc.getSelectedFile();
        selectedFile = file;

        pathToTxtFile = selectedFile.getAbsolutePath().replace(".docx", ".txt");
        TxtFile = new File(pathToTxtFile);

        String zipFilePath = "C:\\Users\\KXK3\\Documents\\ZipTest\\test.zip";
        String destDirectory = "C:\\Users\\KXK3\\Documents\\ZipTest\\temp";
        UnzipUtility unzipper = new UnzipUtility();
        try {
            File zip = new File(zipFilePath);
            File directory = new File(destDirectory);
            FileUtils.copyFile(selectedFile, zip);
            unzipper.UnzipUtility(zip, directory);

            String mediaPath = destDirectory + "/word/media/";
            File mediaDir = new File(mediaPath);

            for (File fil : mediaDir.listFiles()) {
                FileUtils.copyFile(fil,
                        new File("C:\\Users\\KXK3\\Documents\\ZipTest\\Pictures\\" + fil.getName()));
            }

            zip.delete();
            FileUtils.deleteDirectory(directory);

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        //if the txt file doesn't exist, it tries to convert whatever 
        //can be the txt into the actual txt.
        if (!TxtFile.exists()) {
            pathToTxtFile = selectedFile.getAbsolutePath().replace(".docx", "");
            TxtFile = new File(pathToTxtFile);
            pathToTxtFile += ".txt";
            TxtFile.renameTo(new File(pathToTxtFile));
            TxtFile = new File(pathToTxtFile);
        }

        String content;
        String POIContent;

        try {
            content = readTxtFile();
            version = DetermineVersion(content);
            NewExtract ext = new NewExtract();
            ext.extract(content, selectedFile.getAbsolutePath(), version, 1);

        } catch (FileNotFoundException ex) {
            Exceptions.printStackTrace(ex);
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        } catch (ParseException ex) {
            Exceptions.printStackTrace(ex);
        }

    } else {
        //do nothing
    }

}

From source file:com.itemanalysis.jmetrik.swing.GraphPanel.java

public void addJpgMenuItem(final Component parent, JPopupMenu popMenu) {
    JMenuItem mItem = new JMenuItem("Save as JPG...");
    mItem.addActionListener(new ActionListener() {
        @Override/*from ww  w. j av a  2s. c o m*/
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            FileFilter filter1 = new SimpleFilter("jpg", "JPG File (*.jpg)");
            chooser.addChoosableFileFilter(filter1);
            int status = chooser.showSaveDialog(parent);
            if (status == JFileChooser.APPROVE_OPTION) {
                File f = chooser.getSelectedFile();
                try {
                    String fileName = f.getAbsolutePath().toLowerCase();
                    if (!fileName.endsWith("jpg"))
                        fileName += ".jpg";
                    saveAsJPEG(new File(fileName));
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(parent, "IOException: Could not save file", "IOException",
                            JOptionPane.ERROR_MESSAGE);
                }

            }

        }
    });
    popMenu.add(mItem);
}