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:org.streamspinner.harmonica.application.CQGraphTerminal.java

private void show_open_hamql_dialog() {
    FileFilter filter = createFilter();

    JFileChooser jf = new JFileChooser("conf/query/");
    jf.setFileFilter(filter);

    jf.setDialogTitle("HamQL (SpinQL) ?J");

    int returnVal = jf.showOpenDialog(this);
    if (returnVal != JFileChooser.APPROVE_OPTION)
        return;//from  w  w  w  .j  av a  2  s .co m

    File f = jf.getSelectedFile();

    try {
        FileReader reader = new FileReader(f);
        BufferedReader br = new BufferedReader(reader);

        StringBuilder buf = new StringBuilder();
        String tmp = null;
        while ((tmp = br.readLine()) != null) {
            buf.append(tmp + "\n");
        }
        br.close();
        reader.close();

        getJTextArea().setText(buf.toString());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

private void generarReporteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generarReporteActionPerformed
    try {/*ww  w.ja  va2  s  . com*/
        if (servicioMetaData.isEditado()) {
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
            this.aplication.guardaServicio();
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
        }
        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 + "/Reporte-Servicio-" + this.viewServicioModel.getId() + ".xlsx")
                .getCanonicalPath());
        chooser.setSelectedFile(f);
        int returnVal = chooser.showSaveDialog(this.mainFrame);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.WAIT_CURSOR));
            ParametrosReporte param = new ParametrosReporte();
            param.setDestination(chooser.getSelectedFile());
            this.aplication.generaReporte(param);
        }
    } catch (IllegalArgumentException e) {
        //no lo guardo por que tenia horribles errores... tambien especializar la excepcion
    } catch (IOException ex) {
        CostoServicioView.LOGGER.error(ex);
    } finally {
        this.setCursor(java.awt.Cursor.getPredefinedCursor(java.awt.Cursor.DEFAULT_CURSOR));
    }
}

From source file:aurelienribon.gdxsetupui.ui.panels.LibrarySelectionPanel.java

private void browse(String libraryName) {
    File file = libsSelectedFiles.get(libraryName);
    String path = file != null ? file.getPath() : ".";
    JFrame frame = (JFrame) SwingUtilities.getWindowAncestor(this);

    JFileChooser chooser = new JFileChooser(new File(path));
    chooser.setFileFilter(new FileNameExtensionFilter("Zip files (*.zip)", "zip"));
    chooser.setDialogTitle("Please select the zip archive for \"" + libraryName + "\"");

    if (chooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
        select(libraryName, chooser.getSelectedFile());
    }//from www  .  j  a va 2  s. com
}

From source file:com.wcmc.Software.excel.ExportCMAPoints.java

@Override
public void run() {

    Date now = new Date();

    SimpleDateFormat date = new SimpleDateFormat("yyyy");

    String year = date.format(now);

    JFileChooser saveAs = new JFileChooser(System.getProperty("user.home"));
    saveAs.setDialogTitle("Save Standings For The " + year + " Season");
    saveAs.setFileFilter(new FileNameExtensionFilter("Excel 2003 (*.xls)", "xls"));
    if (saveAs.showSaveDialog(Client.window) == JFileChooser.APPROVE_OPTION) {
        File exportFile = null;/* ww  w.j  av  a  2  s.  c  o m*/
        if (!saveAs.getSelectedFile().toString().endsWith(".xls")) {
            exportFile = new File(saveAs.getSelectedFile().getAbsolutePath() + ".xls");
        } else {
            exportFile = saveAs.getSelectedFile();
        }

        try {
            WritableWorkbook excelFile = Workbook.createWorkbook(exportFile);
            System.out.println("Exporting Standings...");
            int sheetNumber = 0;
            ArrayList<ClassItem> classes = Client.ms.rS.classes.getClasses();

            Client.ms.trS.prgExport.setVisible(true);
            Client.ms.trS.prgExport.setPercent(0);
            Client.ms.trS.prgClass.setVisible(true);
            Client.ms.trS.prgClass.setPercent(0);
            Client.ms.trS.overall.setVisible(true);
            Client.ms.trS.classSpecific.setVisible(true);
            for (int i = 0; i < classes.size(); i++) {
                ClassItem c = classes.get(i);
                Client.ms.trS.classSpecific.setText("Class: " + c.getText());
                WritableSheet classSheet = excelFile.createSheet(c.getText().toString(), sheetNumber);
                classSheet.mergeCells(1, 1, 13, 1);
                classSheet.addCell(new Label(1, 1,
                        c.getText().toString() + " - Niagara Motorcycle Raceway - " + year + " Season",
                        headerGrey));
                classSheet.addCell(new Label(1, 3, "Plate #", headerBold));
                classSheet.addCell(new Label(2, 3, "CMA", headerBold));
                classSheet.addCell(new Label(3, 3, "First Name", headerBold));
                classSheet.addCell(new Label(4, 3, "Last Name", headerBold));
                classSheet.addCell(new Label(5, 3, "Total Points", headerBold));
                Client.sc.send(CONST.GET_RACE_DATES + " " + year + CONST.seperator + c.getID());
                String jsonData = null;
                while ((jsonData = Client.sc.getInfo()) == null) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                if (jsonData != null) {

                    JSONParser parse = new JSONParser();
                    JSONObject jsonDates = (JSONObject) parse.parse(jsonData);
                    if (jsonDates != null) {
                        JSONArray jsonDatesArray = (JSONArray) jsonDates.get("dates");
                        JSONArray riderDataArray = (JSONArray) jsonDates.get("riders");
                        if (riderDataArray.size() == 0) {
                            excelFile.removeSheet(sheetNumber);
                            continue;
                        }
                        for (int d = 0; d < jsonDatesArray.size(); d++) {
                            String dateString = (String) jsonDatesArray.get(d);
                            classSheet.mergeCells(6 + (d * 2), 3, 6 + (d * 2) + 1, 3);

                            DateFormat customDateFormat = new DateFormat("MMMM dd");
                            WritableCellFormat dateFormat = new WritableCellFormat(customDateFormat);
                            dateFormat.setBorder(Border.ALL, BorderLineStyle.THICK);
                            dateFormat.setAlignment(Alignment.CENTRE);
                            dateFormat.setFont(arial10bold);
                            SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-M-d");

                            Date eventDate = dateParser.parse(dateString);

                            jxl.write.DateTime dateFormatCell = new jxl.write.DateTime(6 + (d * 2), 3,
                                    eventDate, dateFormat);

                            classSheet.addCell(dateFormatCell);
                            classSheet.addCell(new Label(6 + (d * 2), 5, "POS", dataCenter));
                            classSheet.addCell(new Label(6 + (d * 2) + 1, 5, "Points", dataCenter));
                            classSheet.setColumnView(6 + (d * 2), 10);
                            classSheet.setColumnView(6 + (d * 2) + 1, 10);

                        }

                        classSheet.addCell(new Label(6 + jsonDatesArray.size() * 2, 3, "City", headerBold));
                        classSheet.addCell(new Label(7 + jsonDatesArray.size() * 2, 3, "Sponsors", headerBold));
                        classSheet.setColumnView(6 + jsonDatesArray.size() * 2, 25);
                        classSheet.setColumnView(7 + jsonDatesArray.size() * 2, 75);

                        for (int r = 0; r < riderDataArray.size(); r++) {
                            JSONObject rider = (JSONObject) riderDataArray.get(r);
                            JSONObject bike = (JSONObject) rider.get("bike");
                            if (bike != null) {
                                classSheet.addCell(new Number(1, 6 + r, (long) bike.get("plate"), pointsBold));
                            }
                            classSheet.addCell(new Label(2, 6 + r, (String) rider.get("license"), pointsBold));
                            classSheet
                                    .addCell(new Label(3, 6 + r, (String) rider.get("first_name"), dataCenter));
                            classSheet
                                    .addCell(new Label(4, 6 + r, (String) rider.get("last_name"), dataCenter));
                            classSheet
                                    .addCell(new Number(5, 6 + r, (long) rider.get("totalPoints"), pointsBold));

                            JSONArray events = (JSONArray) rider.get("events");
                            boolean hasEvent = false;
                            for (int d = 0; d < jsonDatesArray.size(); d++) {
                                hasEvent = false;
                                for (int e = 0; e < events.size(); e++) {
                                    String dateString = (String) jsonDatesArray.get(d);
                                    JSONObject event = (JSONObject) events.get(e);
                                    if (event.get("date").equals(dateString)) {
                                        classSheet.addCell(new Number(6 + (d * 2), 6 + r,
                                                (long) event.get("position"), dataCenter));
                                        classSheet.addCell(new Number(6 + (d * 2) + 1, 6 + r,
                                                (long) event.get("points"), dataCenter));
                                        hasEvent = true;
                                    }
                                }
                                if (!hasEvent) {
                                    classSheet.addCell(new Label(6 + (d * 2), 6 + r, "", dataCenter));
                                    classSheet.addCell(new Label(6 + (d * 2) + 1, 6 + r, "", dataCenter));
                                }
                            }
                            classSheet.addCell(new Label(6 + (jsonDatesArray.size() * 2), 6 + r,
                                    (String) rider.get("city"), dataCenter));
                            classSheet.addCell(new Label(7 + (jsonDatesArray.size() * 2), 6 + r,
                                    (String) rider.get("sponsors"), dataWrapped));
                            Client.ms.trS.prgClass
                                    .setPercent(((double) r / (double) riderDataArray.size()) * 100);
                        }
                    }
                }

                // Set Widths
                classSheet.setRowView(3, 300);

                classSheet.setColumnView(1, 10);
                classSheet.setColumnView(2, 10);
                classSheet.setColumnView(3, 18);
                classSheet.setColumnView(4, 18);
                classSheet.setColumnView(5, 15);
                sheetNumber++;

                Client.ms.trS.prgExport
                        .setPercent(((double) i / (double) Client.ms.rS.classes.getClasses().size()) * 100);
            }
            excelFile.write();
            excelFile.close();

            WorkBook sortedWorkbook = new WorkBook();
            try {
                sortedWorkbook.read(new FileInputStream(exportFile));
                for (int i = 0; i < sheetNumber; i++) {
                    sortedWorkbook.setSheet(i);
                    sortedWorkbook.sort(6, 1, 60, 60, true, -5, 0, 0);
                }
                sortedWorkbook.setSheet(0);
                FileOutputStream out = new FileOutputStream(exportFile);
                sortedWorkbook.write(out);
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            Client.ms.trS.prgExport.setVisible(false);
            Client.ms.trS.prgClass.setVisible(false);
            Client.ms.trS.overall.setVisible(false);
            Client.ms.trS.classSpecific.setVisible(false);
        } catch (IOException | WriteException | ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (java.text.ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:com.genericworkflownodes.knime.nodes.io.OutputFileNodeDialog.java

/**
 * New pane for configuring MimeFileExporter node dialog.
 *//*from w  w w  .  j  a  v  a2  s  .c  o  m*/
public OutputFileNodeDialog(final String settingsName) {
    this.settingsName = settingsName;
    dialogPanel = new JPanel();
    componentContainer = new JPanel();
    textField = new JTextField();
    textField.setPreferredSize(new Dimension(300, textField.getPreferredSize().height));
    searchButton = new JButton("Browse");
    searchButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final JFileChooser jfc = new JFileChooser();
            if (!"".equals(textField.getText().trim())
                    && new File(textField.getText().trim()).getParent() != null) {
                jfc.setCurrentDirectory(new File(textField.getText().trim()).getParentFile());
            }

            jfc.setAcceptAllFileFilterUsed(false);
            jfc.setFileFilter(extensionFilter);

            // int returnVal = jfc.showSaveDialog(dialogPanel);
            jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int returnVal = jfc.showDialog(dialogPanel, "Select output file");
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                // validate extension
                if (!extensionFilter.accept(jfc.getSelectedFile())) {
                    String message = "The selected output file has an invalid file extension.\n";
                    if (extensionFilter.getExtensions().length == 1) {
                        message += "Please choose a file with extension: " + extensionFilter.getExtensions()[0];
                    } else {
                        message += "Please choose a file with on of the following extensions: ";
                        message += StringUtils.join(extensionFilter.getExtensions(), ", ");
                    }
                    JOptionPane.showMessageDialog(getPanel(), message, "Selected Output File is invalid.",
                            JOptionPane.WARNING_MESSAGE);
                }
                textField.setText(jfc.getSelectedFile().getAbsolutePath());
            }
        }
    });
    setLayout();
    addComponents();

    addTab("Choose File", dialogPanel);
}

From source file:com.egangotri.transliteratorAsSwing.TransliteratorJFrame.java

public void chooseFile(JTextArea jta) {
    JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(false);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("TEXT FILES", "txt", "text");
    chooser.setFileFilter(filter);

    int option = chooser.showOpenDialog(this);
    if (option == JFileChooser.APPROVE_OPTION) {
        if (chooser.getSelectedFile() != null) {
            Log.info("You chose to open this file: " + chooser.getSelectedFile().getPath());
            String path = chooser.getSelectedFile().getPath();
            FileIO.readFile(new File(path), jta);
        }//  w  ww. jav a  2  s.  co  m
    }
}

From source file:com.stanley.captioner.MainFrame.java

private void addButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_addButtonActionPerformed
{//GEN-HEADEREND:event_addButtonActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setMultiSelectionEnabled(true);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("MP4 VIDEOS", "mp4", "mpeg");
    fileChooser.setFileFilter(filter);
    if (lastAddDirectory != null) {
        fileChooser.setCurrentDirectory(lastAddDirectory);
    }/*w w  w .j a va  2  s.  c o m*/
    int returnValue = fileChooser.showOpenDialog(this);

    if (returnValue == JFileChooser.APPROVE_OPTION) {
        lastAddDirectory = fileChooser.getCurrentDirectory();

        DefaultTableModel model = (DefaultTableModel) videoTable.getModel();
        File files[] = fileChooser.getSelectedFiles();
        for (File file : files) {
            boolean alreadyExists = false;
            for (int i = model.getRowCount() - 1; i >= 0; i--) {
                String path = (String) model.getValueAt(i, 0);
                if (file.getAbsolutePath().equals(path)) {
                    alreadyExists = true;
                }
            }

            if (!alreadyExists) {
                model.addRow(getVideoInfo(file));
            }
        }
    }
}

From source file:InterfaceModule.JRobert.java

private File loadFile() {
    JFileChooser chooser = new JFileChooser(System.getProperty("user.dir") + "/saves/");
    FileNameExtensionFilter filter = new FileNameExtensionFilter("TXT file", "txt");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        return chooser.getSelectedFile();
    } else/*from   w  w w. j a  v a 2  s  .  co  m*/
        return null;
}

From source file:au.org.ala.delta.intkey.ui.DefineButtonDialog.java

@Action
public void DefineButtonDialog_Browse() {
    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter(fileFilterDescription,
            new String[] { "bmp", "png" });
    chooser.setFileFilter(filter);

    int returnVal = chooser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File selectedFile = chooser.getSelectedFile();
        _txtFldFileName.setText(selectedFile.getAbsolutePath());
    }// ww  w .j  ava2 s  . c o  m
}

From source file:au.org.ala.delta.intkey.ui.UIUtils.java

/**
 * Prompts for a file using the file chooser dialog
 * /*from   ww w  .jav  a2  s  .co m*/
 * @param fileExtensions
 *            Accepted file extensions - must be null if filePrefixes is
 *            non-null
 * @param filePrefixes
 *            Accepted file prefixes - must be null if fileExtensions is
 *            non-null
 * @param description
 *            Description of the acceptable files
 * @param createFileIfNonExistant
 *            if true, the file will be created if it does not exist. Also,
 *            the system's "save" will be used instead of the "open" dialog.
 * @param startBrowseDirectory
 *            The directory that the file chooser should start in
 * @param parent
 *            parent component for the file chooser
 * @return the selected file, or null if no file was selected.
 * @throws IOException
 */
public static File promptForFile(List<String> fileExtensions, List<String> filePrefixes,
        final String description, boolean createFileIfNonExistant, File startBrowseDirectory, Component parent)
        throws IOException {
    if (fileExtensions != null && filePrefixes != null) {
        throw new IllegalArgumentException(
                "Only one of the file extensions or file prefixes should be non-null");
    }

    JFileChooser chooser = new JFileChooser(startBrowseDirectory);
    FileFilter filter;

    if (fileExtensions != null) {
        String[] extensionsArray = new String[fileExtensions.size()];
        fileExtensions.toArray(extensionsArray);
        filter = new FileNameExtensionFilter(description, extensionsArray);
    } else {
        final String[] prefixesArray = new String[filePrefixes.size()];
        filePrefixes.toArray(prefixesArray);
        filter = new FileFilter() {

            @Override
            public String getDescription() {
                return description;
            }

            @Override
            public boolean accept(File f) {
                if (f.isDirectory()) {
                    return true;
                } else {
                    return StringUtils.startsWithAny(f.getName(), prefixesArray);
                }
            }
        };
    }
    chooser.setFileFilter(filter);

    int returnVal;

    if (createFileIfNonExistant) {
        returnVal = chooser.showSaveDialog(parent);
    } else {
        returnVal = chooser.showOpenDialog(parent);
    }

    if (returnVal == JFileChooser.APPROVE_OPTION) {

        if (createFileIfNonExistant) {
            File file = chooser.getSelectedFile();

            if (!file.exists()) {
                // if only one file extension was supplied and the filename
                // does
                // not end with this extension, add it before
                // creating the file
                if (fileExtensions.size() == 1) {
                    String extension = fileExtensions.get(0);
                    String filePath = chooser.getSelectedFile().getAbsolutePath();
                    if (!filePath.endsWith(extension)) {
                        file = new File(filePath + "." + extension);
                    }
                }

                file.createNewFile();
            }
            return file;
        } else {
            return chooser.getSelectedFile();
        }
    } else {
        return null;
    }
}