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:ImageIOTest.java

/**
 * Save the current image in a file/*from  w  w  w.jav  a  2 s .c  o m*/
 * @param formatName the file format
 */
public void saveFile(final String formatName) {
    if (images == null)
        return;
    Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName(formatName);
    ImageWriter writer = iter.next();
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    String[] extensions = writer.getOriginatingProvider().getFileSuffixes();
    chooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions));

    int r = chooser.showSaveDialog(this);
    if (r != JFileChooser.APPROVE_OPTION)
        return;
    File f = chooser.getSelectedFile();
    try {
        ImageOutputStream imageOut = ImageIO.createImageOutputStream(f);
        writer.setOutput(imageOut);

        writer.write(new IIOImage(images[0], null, null));
        for (int i = 1; i < images.length; i++) {
            IIOImage iioImage = new IIOImage(images[i], null, null);
            if (writer.canInsertImage(i))
                writer.writeInsert(i, iioImage, null);
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, e);
    }
}

From source file:org.pmedv.jake.commands.AddFilesCommand.java

@Override
public void execute() {

    final ApplicationContext ctx = AppContext.getApplicationContext();
    final ApplicationWindow win = (ApplicationWindow) ctx.getBean(BeanDirectory.WINDOW_APPLICATION);

    /**/*w w w.  j a v  a  2s. c  om*/
     * Get last selected folder to simplify file browsing
     */

    if (AppContext.getLastSelectedFolder() == null)
        AppContext.setLastSelectedFolder(System.getProperty("user.home"));

    JFileChooser fc = new JFileChooser(AppContext.getLastSelectedFolder());
    fc.setDialogTitle("Add files");
    fc.setMultiSelectionEnabled(true);
    fc.setFileFilter(new MP3Filter());

    int result = fc.showOpenDialog(win);

    if (result == JFileChooser.CANCEL_OPTION)
        return;

    File[] files = fc.getSelectedFiles();

    PlayerView view = JakeUtil.getCurrentActivePlayer();

    if (view == null) {

        ArrayList<File> fileList = new ArrayList<File>();

        for (int i = 0; i < files.length; i++)
            fileList.add(files[i]);

        final PlayerController controller = new PlayerController(fileList);
        JakeUtil.updateRecentFiles(fc.getSelectedFile().getAbsolutePath());
        AppContext.setLastSelectedFolder(fc.getSelectedFiles()[0].getParentFile().getAbsolutePath());

        View v = new View(fc.getSelectedFile().getAbsolutePath(), null, controller.getPlayerView());

        v.addListener(new DockingWindowAdapter() {

            @Override
            public void windowClosing(DockingWindow arg0) throws OperationAbortedException {

                controller.getPlayer().close();
                controller.getPlayFileCommand().setPlaying(false);
            }

        });

        openEditor(v);
    }

    else {

        if (files.length >= 1) {

            AppContext.setLastSelectedFolder(fc.getSelectedFiles()[0].getParentFile().getAbsolutePath());
            JakeUtil.updateRecentFiles(fc.getSelectedFiles()[0].getParentFile().getAbsolutePath());

            FileTableModel model = (FileTableModel) view.getFileTable().getModel();

            for (int i = 0; i < files.length; i++) {
                model.addObject(files[i]);
            }

        }

    }

}

From source file:com.intuit.tank.proxy.settings.ui.ProxyConfigDialog.java

protected void openConfig() {
    JFileChooser fileChooser = new JFileChooser();
    File file = new File(".");
    fileChooser.setCurrentDirectory(file);
    fileChooser.setAcceptAllFileFilterUsed(false);
    fileChooser.setFileFilter(new XmlFileFilter());
    int showOpenDialog = fileChooser.showOpenDialog(this);

    if (showOpenDialog == JFileChooser.APPROVE_OPTION) {
        configHandler.setConfigFile(fileChooser.getSelectedFile().getAbsolutePath());
        getProxyConfigPanel().update();//from w w w.  java  2s . com
    }
}

From source file:XPathTest.java

/**
     * Open a file and load the document.
     *//*from   w  w w. j a  v a  2 s.  c  om*/
    public void openFile() {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));

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

            public String getDescription() {
                return "XML files";
            }
        });
        int r = chooser.showOpenDialog(this);
        if (r != JFileChooser.APPROVE_OPTION)
            return;
        File f = chooser.getSelectedFile();
        try {
            byte[] bytes = new byte[(int) f.length()];
            new FileInputStream(f).read(bytes);
            docText.setText(new String(bytes));
            doc = builder.parse(f);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this, e);
        } catch (SAXException e) {
            JOptionPane.showMessageDialog(this, e);
        }
    }

From source file:view.MainFrame.java

private void menuItemOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemOpenActionPerformed
    // TODO add your handling code here:
    JFileChooser filech = new JFileChooser();
    filech.setFileSelectionMode(JFileChooser.FILES_ONLY);
    filech.setFileFilter(new FileNameExtensionFilter("WAV Files", "wav"));
    int ret = filech.showOpenDialog(this);

    if (ret == JFileChooser.APPROVE_OPTION) {
        try {/*  w w w.  j a va 2s  .  c o m*/
            wavFile = WavFile.openWavFile(filech.getSelectedFile());
            textArea.append(wavFile.getInfoString());
            samples = new double[wavFile.getNumChannels() * (int) wavFile.getSampleRate()];
            int nFrames = wavFile.readFrames(samples, (int) wavFile.getSampleRate());
            textArea.append(nFrames + " frames lidos.\n");

            double valuesX[] = new double[samples.length];
            for (int i = 0; i < samples.length; i++) {
                valuesX[i] = i;
            }

            showChart(wavFile.getNumChannels() * (int) wavFile.getSampleRate(), samples, valuesX, "Amostra",
                    "Amplitude", "Amplitude das Amostras do ?udio", "Audio");
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (WavFileException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

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

@Ignore
@org.junit.Test/*from  w ww .  j a  v a 2 s  .  c om*/
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, p1Start = null, p1End = null, p2Start = null, p2End = null, otStart = null,
                otEnd = null;
        Date scdate = null;

        // read from select file
        while ((strLine = br.readLine()) != null) {
            String[] parts = strLine.split(" ");

            // check if not first record or sysid change will save in table scandata 
            if (sysid != null && !sysid.equals(parts[0])) {
                // rule if whatever employee register will get standard hour 8 hrs
                if (p1Start != null || p2End != null) {
                    ScanRule scanRule = scanDao.findScanRuleBySysId(sysid);
                    p1Start = scanRule.getP1start();
                    p2End = scanRule.getP2end();
                }

                // set up data in entity
                ScanDataKey scanDataKey = new ScanDataKey(sysid, scdate);
                ScanData scanData = new ScanData(scanDataKey, "1985", p1Start, p1End, p2Start, p2End, otStart,
                        otEnd);
                // remove old record (key is sysid and scdate)
                gennericDao.remove(scanData);
                gennericDao.create(scanData);

                //clear 
                p1Start = null;
                p1End = null;
                p2Start = null;
                p2End = null;
                otStart = null;
                otEnd = null;

            }

            sysid = parts[0];
            scdate = new SimpleDateFormat("yyyyMMdd", Locale.US).parse(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();
        }

        ScanDataKey scanDataKey = new ScanDataKey(sysid, scdate);
        ScanData scanData = new ScanData(scanDataKey, "1985", p1Start, p1End, p2Start, p2End, otStart, otEnd);
        gennericDao.remove(scanData);
        gennericDao.create(scanData);

        br.close();

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }

}

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

@Ignore
@org.junit.Test/*from   w  w  w .j  a  va2s  .  c  om*/
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;
        String scode = "1985";
        StringBuilder mySql = new StringBuilder(
                "INSERT INTO scandata(sc_sysid,sc_scode,scdate,p1start,p2end) VALUES ");

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

        // read from select file
        while ((strLine = br.readLine()) != null) {
            String[] parts = strLine.split(" ");

            // check if not first record or sysid change will save in table scandata 
            if (sysid != null && !sysid.equals(parts[0])) {
                mySql = mySql.append(" ('").append(sysid).append("','").append(scode).append("','")
                        .append(scdate).append("','").append(p1Start).append("','").append(p2End).append("'),");

                p1Start = null;
                p1End = null;
                p2Start = null;
                p2End = null;
                otStart = null;
                otEnd = null;

            }

            //clear 
            sysid = parts[0];
            scdate = new StringBuffer(parts[1]).insert(parts[1].length() - 2, "-").toString();
            scdate = new StringBuffer(scdate).insert(scdate.length() - 5, "-").toString();

            String timeString = new StringBuffer(parts[5]).insert(parts[5].length() - 2, ":").toString();

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

        mySql = mySql.append(" ('").append(sysid).append("','").append(scode).append("','").append(scdate)
                .append("','").append(p1Start).append("','").append(p2End).append("')");

        scanDao.executeSQL(mySql.toString());

        br.close();

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }

}

From source file:de.stefanwndelmann.zy1270logger.ZY1270LoggerMain.java

private void saveCSVButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveCSVButtonActionPerformed
    // TODO add your handling code here:
    String data = getCSVData();//from w  ww  . j av a 2  s .  c om
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv"));
    int retrival = chooser.showSaveDialog(null);
    if (retrival == JFileChooser.APPROVE_OPTION) {
        try (FileWriter fw = new FileWriter(chooser.getSelectedFile() + ".csv")) {
            fw.write(data);
        } catch (IOException ex) {
            Logger.getLogger(ZY1270LoggerMain.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

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

@Ignore
@org.junit.Test/*w  w  w.j  a v a  2 s .  c o 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;

        // read from select file
        while ((strLine = br.readLine()) != null) {
            String[] parts = strLine.split(" ");

            // check if not first record or sysid change will save in table scandata 
            if (sysid != null && !sysid.equals(parts[0])) {

                List<Object> lst = new ArrayList<Object>();

                scanDao.deleteScanDataBySysId_Sdate(sysid, scdate);
                scanDao.insertScanData(sysid, "1985", scdate, p1Start, p1End, p2Start, p2End, otStart, otEnd);

                p1Start = null;
                p1End = null;
                p2Start = null;
                p2End = null;
                otStart = null;
                otEnd = null;

            }

            //clear 
            sysid = parts[0];
            scdate = new StringBuffer(parts[1]).insert(parts[1].length() - 2, "-").toString();
            scdate = new StringBuffer(scdate).insert(scdate.length() - 5, "-").toString();

            String timeString = new StringBuffer(parts[5]).insert(parts[5].length() - 2, ":").toString();

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

        }

        scanDao.deleteScanDataBySysId_Sdate(sysid, scdate);
        scanDao.insertScanData(sysid, "1985", scdate, p1Start, p1End, p2Start, p2End, otStart, otEnd);

        br.close();

        //last line
        //            if (p1Start != null || p2End != null) {
        //                ScanRule scanRule = scanDao.findScanRuleBySysId(sysid);
        //                p1Start = scanRule.getP1start();
        //                p2End = scanRule.getP2end();
        //            }
        //            ScanDataKey scanDataKey = new ScanDataKey(sysid, scdate);
        //            ScanData scanData = new ScanData(scanDataKey, "1985", p1Start, p1End, p2Start, p2End, otStart, otEnd);
        //            gennericDao.remove(scanData);
        //            gennericDao.create(scanData);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }

}

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

private Config promptForConfig() {
    JFileChooser fc = new JFileChooser("config");
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    FileFilter filter = new FileNameExtensionFilter("Text Config File", "txt");
    fc.setFileFilter(filter);
    fc.setMultiSelectionEnabled(false);// w  w w.  j av a 2 s. com
    int ret = fc.showOpenDialog(frame);
    if (ret == JFileChooser.APPROVE_OPTION) {
        try {
            return new ConfigFile(fc.getSelectedFile().getAbsolutePath());
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }
    return null;
}