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: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/*from ww  w  .  ja va  2  s. c  o m*/
        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:ch.tatool.app.export.FileDataExporter.java

private String getStorageDirectory(Component parentFrame) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(new FileFilter() {

        @Override//from   w w w . ja va  2  s.co  m
        public String getDescription() {
            return "CSV (*.csv)";
        }

        @Override
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }

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

            return false;

        }
    });
    chooser.setAcceptAllFileFilterUsed(false);
    // chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setMultiSelectionEnabled(false);
    int returnVal = chooser.showSaveDialog(parentFrame);
    if (returnVal == JFileChooser.APPROVE_OPTION) {

        File f = chooser.getSelectedFile();
        String filename = "";
        if (f == null) {
            throw new RuntimeException();
        }
        String extension = getExtension(f);
        if (extension == null || !getExtension(f).equals("csv")) {
            filename = f + ".csv";
        } else {
            filename = f.getPath();
        }
        return filename;
    } else {
        return null;
    }
}

From source file:edu.umich.robot.GuiApplication.java

/**
 * <p>//from ww  w.  jav a  2s.c om
 * Firing up this application requires a configuration file. If no
 * configuration file is presented on the command line, this is called to
 * prompt the user to select a configuration file.
 * 
 * <p>
 * Future work should probably include some default instead of doing this.
 * 
 * @return The selected, loaded configuration file.
 */
public static Config promptForConfig(Component parent) {

    System.out.println("CLASSPATH: " + System.getenv("CLASSPATH"));
    System.out.println("DYLD_LIBRARY_PATH: " + System.getenv("DYLD_LIBRARY_PATH"));
    System.out.println("LD_LIBRARY_PATH: " + System.getenv("LD_LIBRARY_PATH"));
    System.out.println("SOAR_HOME: " + System.getenv("SOAR_HOME"));
    System.out.println("java.library.path: " + System.getProperty("java.library.path"));

    JFileChooser fc = new JFileChooser(System.getProperty("user.dir"));
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    FileFilter filter = new FileNameExtensionFilter("Text Config File", "txt");
    fc.setFileFilter(filter);
    fc.setMultiSelectionEnabled(false);
    int ret = fc.showOpenDialog(parent);
    if (ret == JFileChooser.APPROVE_OPTION) {
        try {
            return new ConfigFile(fc.getSelectedFile().getAbsolutePath());
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }
    return null;
}

From source file:pt.lsts.neptus.console.plugins.AirOSPeers.java

public AirOSPeers(ConsoleLayout console) {
    super(console);
    setLayout(new BorderLayout());
    chart = ChartFactory.createTimeSeriesChart(null, "Time of day", "Link Quality", tsc, true, true, true);
    chart.getPlot().setBackgroundPaint(Color.black);
    cpanel = new ChartPanel(chart);
    add(cpanel, BorderLayout.CENTER);
    cpanel.getPopupMenu().add(I18n.text("Load Addresses")).addActionListener(new ActionListener() {
        @Override//from  w  w w .  java  2  s .c om
        public void actionPerformed(ActionEvent e) {
            try {
                JFileChooser chooser = new JFileChooser();
                chooser.setFileFilter(GuiUtils.getCustomFileFilter("CSV Files", "csv"));
                chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                int op = chooser.showOpenDialog(AirOSPeers.this);
                if (op == JFileChooser.APPROVE_OPTION)
                    WiFiMacAddresses.parseAddresses(new FileReader(chooser.getSelectedFile()));
            } catch (Exception ex) {
                GuiUtils.errorMessage(getConsole(), ex);
                ex.printStackTrace();
            }
        }
    });
    cpanel.getPopupMenu().addSeparator();
    cpanel.getPopupMenu().add(I18n.text("Clear")).addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            tsc.removeAllSeries();
        }
    });
}

From source file:PreferencesTest.java

public PreferencesFrame() {
    // get position, size, title from preferences

    Preferences root = Preferences.userRoot();
    final Preferences node = root.node("/com/horstmann/corejava");
    int left = node.getInt("left", 0);
    int top = node.getInt("top", 0);
    int width = node.getInt("width", DEFAULT_WIDTH);
    int height = node.getInt("height", DEFAULT_HEIGHT);
    setBounds(left, top, width, height);

    // if no title given, ask user

    String title = node.get("title", "");
    if (title.equals(""))
        title = JOptionPane.showInputDialog("Please supply a frame title:");
    if (title == null)
        title = "";
    setTitle(title);/*from   www . j  ava 2  s. c o  m*/

    // set up file chooser that shows XML files

    final JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));

    // accept all files ending with .xml
    chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
        public boolean accept(File f) {
            return f.getName().toLowerCase().endsWith(".xml") || f.isDirectory();
        }

        public String getDescription() {
            return "XML files";
        }
    });

    // set up menus
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    JMenu menu = new JMenu("File");
    menuBar.add(menu);

    JMenuItem exportItem = new JMenuItem("Export preferences");
    menu.add(exportItem);
    exportItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            if (chooser.showSaveDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION) {
                try {
                    OutputStream out = new FileOutputStream(chooser.getSelectedFile());
                    node.exportSubtree(out);
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });

    JMenuItem importItem = new JMenuItem("Import preferences");
    menu.add(importItem);
    importItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            if (chooser.showOpenDialog(PreferencesFrame.this) == JFileChooser.APPROVE_OPTION) {
                try {
                    InputStream in = new FileInputStream(chooser.getSelectedFile());
                    Preferences.importPreferences(in);
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });

    JMenuItem exitItem = new JMenuItem("Exit");
    menu.add(exitItem);
    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            node.putInt("left", getX());
            node.putInt("top", getY());
            node.putInt("width", getWidth());
            node.putInt("height", getHeight());
            node.put("title", getTitle());
            System.exit(0);
        }
    });
}

From source file:org.nekorp.workflow.desktop.view.FormatoProgramacionView.java

private void importarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_importarActionPerformed
    try {/*from  w w w .  jav  a 2s  .c  o  m*/
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Hojas de clculo", "xlsx");
        chooser.setFileFilter(filter);
        String homePath = System.getProperty("user.home");
        File f = new File(new File(homePath).getCanonicalPath());
        chooser.setSelectedFile(f);
        int returnVal = chooser.showOpenDialog(this.mainFrame);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
            this.application.importarArchivo(chooser.getSelectedFile());
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
        }
    } catch (IOException ex) {
        FormatoProgramacionView.LOGGER.error(ex);
    }
}

From source file:ImageIOTest.java

/**
 * Open a file and load the images.//from   w  w w .ja v  a 2  s .c  o m
 */
public void openFile() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    String[] extensions = ImageIO.getReaderFileSuffixes();
    chooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions));
    int r = chooser.showOpenDialog(this);
    if (r != JFileChooser.APPROVE_OPTION)
        return;
    File f = chooser.getSelectedFile();
    Box box = Box.createVerticalBox();
    try {
        String name = f.getName();
        String suffix = name.substring(name.lastIndexOf('.') + 1);
        Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
        ImageReader reader = iter.next();
        ImageInputStream imageIn = ImageIO.createImageInputStream(f);
        reader.setInput(imageIn);
        int count = reader.getNumImages(true);
        images = new BufferedImage[count];
        for (int i = 0; i < count; i++) {
            images[i] = reader.read(i);
            box.add(new JLabel(new ImageIcon(images[i])));
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, e);
    }
    setContentPane(new JScrollPane(box));
    validate();
}

From source file:ImageProcessingTest.java

/**
 * Open a file and load the image./* w  w  w .  j a v  a  2s . c  om*/
 */
public void openFile() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    String[] extensions = ImageIO.getReaderFileSuffixes();
    chooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions));
    int r = chooser.showOpenDialog(this);
    if (r != JFileChooser.APPROVE_OPTION)
        return;

    try {
        Image img = ImageIO.read(chooser.getSelectedFile());
        image = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
        image.getGraphics().drawImage(img, 0, 0, null);
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, e);
    }
    repaint();
}

From source file:com.itd.dbmrgdao.TestTime4.java

@Ignore
@org.junit.Test/*from  w w  w.  j  a va 2 s .  co  m*/
public void test() throws ParseException {
    String newTab = "\t";
    String[] sysidLine;

    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Text File", "txt");
    chooser.setFileFilter(filter);
    chooser.showOpenDialog(null);
    File f = chooser.getSelectedFile();

    String filename = f.getAbsolutePath();
    try {
        FileReader reader = new FileReader(filename);
        BufferedReader br = new BufferedReader(reader);
        String strLine;

        String sysid = null, scdate = null, p1Start = null, p1End = null, p2Start = null, p2End = null,
                otStart = null, otEnd = null;

        StringBuilder mySql = new StringBuilder(
                "INSERT INTO scandata(sc_sysid,sc_scode,scdate,p1start,p1end,p2start,p2end,otstart,otend) VALUES (?,?,?,?,?,?,?,?,?)");

        while ((strLine = br.readLine()) != null) {
            String[] parts = strLine.split(" ");

            if (sysid != null && !sysid.equals(parts[0])) {
                mySql = mySql.append(", (").append(sysid).append(",\"1985\"").append(",").append(scdate)
                        .append(",").append(p1Start).append(",").append(p1End).append(",").append(p2Start)
                        .append(",").append(p2End).append(",").append(otStart).append(",").append(otEnd)
                        .append(")");

                //                    if (p1Start != null || p2End != null) {
                //                        ScanRule scanRule = scanDao.findScanRuleBySysId(sysid);
                //                        p1Start = scanRule.getP1start();
                //                        p2End = scanRule.getP2end();
                //                    }
                //                    ScanDataTest scanData = new ScanDataTest(sysid, scdate, p1Start, p2End);

                p1Start = null;
                p2End = null;

            }

            sysid = parts[0];
            scdate = parts[1];

            if (parts[6].equals("01")) {
                p1Start = CompareTime(p1Start, parts[5], "01");
            } else {
                p2End = CompareTime(p2End, parts[5], "04");
            }

        }

        //last line
        //            if (p1Start != null || p2End != null) {
        //                ScanRule scanRule = scanDao.findScanRuleBySysId(sysid);
        //                p1Start = scanRule.getP1start();
        //                p2End = scanRule.getP2end();
        //            }
        //            ScanDataTest scanData = new ScanDataTest(sysid, scdate, p1Start, p2End);
        //            System.out.println(scanData);
        br.close();

    } catch (Exception e) {

        JOptionPane.showMessageDialog(null, e);

    }

}

From source file:com.seanmadden.net.fast.FastInterpretype.java

public boolean saveLogToFile() {
    JFileChooser jfc = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
    jfc.setFileFilter(filter);
    int retVal = jfc.showSaveDialog(null);
    if (retVal == JFileChooser.APPROVE_OPTION) {
        String filename = jfc.getSelectedFile().getPath();
        mw.saveWindowToFile(filename);//from w ww . j a  va  2 s.c  o m
        return true;
    }
    return false;
}