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.jwebsocket.ui.TestDialog.java

/**
 *
 * @param aDefaultFilename/*from w  w  w.  ja  v a 2 s.  c o  m*/
 */
public void saveLogs(String aDefaultFilename) {
    if (aDefaultFilename == null || aDefaultFilename.equals("")) {
        aDefaultFilename = "jWebSocketTests_" + new SimpleDateFormat("YYYY-MM-dd").format(new Date()) + ".log";
    }
    JFileChooser lChooser = new JFileChooser();
    FileNameExtensionFilter lFilter = new FileNameExtensionFilter("*.log files", "log");
    lChooser.setFileFilter(lFilter);
    lChooser.setSelectedFile(new File(aDefaultFilename));
    int lReturnVal = lChooser.showSaveDialog(this);
    if (lReturnVal == JFileChooser.APPROVE_OPTION) {
        FileWriter lWriter = null;
        try {
            File lFile = lChooser.getSelectedFile();
            lWriter = new FileWriter(lFile);
            lWriter.write(txaLog.getText());
        } catch (IOException aException) {
            mLog(aException.getMessage());
        } finally {
            try {
                if (lWriter != null) {
                    lWriter.close();
                }
            } catch (IOException aIoException) {
                mLog(aIoException.getMessage());
            }
        }
    }
}

From source file:org.kuali.test.ui.components.panels.FileTestPanel.java

/**
 *
 * @param e// ww w  .j  a  v a2s .  co m
 */
@Override
protected void handleUnprocessedActionEvent(ActionEvent e) {
    if (Constants.FILE_SEARCH_ACTION.equals(e.getActionCommand())) {
        Preferences proot = Preferences.userRoot();
        Preferences node = proot.node(Constants.PREFS_FILES_NODE);

        String lastDir = node.get(Constants.PREFS_LAST_FILE_TEST_DIR, System.getProperty("user.home"));

        JFileChooser chooser = new JFileChooser(lastDir);
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

        chooser.setFileFilter(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return (f.isDirectory() && f.exists());
            }

            @Override
            public String getDescription() {
                return "file inquiry directory";
            }
        });

        int returnVal = chooser.showOpenDialog(getMainframe());
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File f = chooser.getSelectedFile();
            fileDirectory.setText(f.getPath());
            node.put(Constants.PREFS_LAST_FILE_TEST_DIR, f.getPath());
        }
    } else if (Constants.FILE_EXISTS.equals(e.getActionCommand())) {
        getFileCheckCondition(Constants.FILE_DOES_NOT_EXIST).setSelected(false);
        getFileCheckCondition(Constants.FILE_SIZE_GREATER_THAN_ZERO).setEnabled(true);
        getFileCheckCondition(Constants.FILE_CREATED_TODAY).setEnabled(true);
        getFileCheckCondition(Constants.FILE_CREATED_YESTERDAY).setEnabled(true);
        containingText.setEnabled(true);
    } else if (Constants.FILE_DOES_NOT_EXIST.equals(e.getActionCommand())) {
        getFileCheckCondition(Constants.FILE_EXISTS).setSelected(false);
        getFileCheckCondition(Constants.FILE_SIZE_GREATER_THAN_ZERO).setSelected(false);
        getFileCheckCondition(Constants.FILE_SIZE_GREATER_THAN_ZERO).setEnabled(false);
        getFileCheckCondition(Constants.FILE_CREATED_TODAY).setSelected(false);
        getFileCheckCondition(Constants.FILE_CREATED_TODAY).setEnabled(false);
        getFileCheckCondition(Constants.FILE_CREATED_YESTERDAY).setSelected(false);
        getFileCheckCondition(Constants.FILE_CREATED_YESTERDAY).setEnabled(false);
        containingText.setText("");
        containingText.setEnabled(false);
    } else if (Constants.FILE_CREATED_TODAY.equals(e.getActionCommand())) {
        getFileCheckCondition(Constants.FILE_CREATED_YESTERDAY).setSelected(false);
    } else if (Constants.FILE_CREATED_YESTERDAY.equals(e.getActionCommand())) {
        getFileCheckCondition(Constants.FILE_CREATED_TODAY).setSelected(false);
    }
}

From source file:org.languagetool.gui.Main.java

private void saveFile(boolean newFile) {
    if (currentFile == null || newFile) {
        JFileChooser jfc = new JFileChooser();
        jfc.setFileFilter(new PlainTextFileFilter());
        jfc.showSaveDialog(frame);//from   ww w . j a va  2 s. co m

        File file = jfc.getSelectedFile();
        if (file == null) { // user clicked cancel
            return;
        }
        currentFile = file;
        bom = null;
        updateTitle();
    }
    try {
        if (bom != null) {
            FileUtils.writeByteArrayToFile(currentFile, bom.getBytes());
            FileUtils.write(currentFile, textArea.getText(), bom.getCharsetName(), true);
        } else {
            FileUtils.write(currentFile, textArea.getText(), Charset.defaultCharset());
        }
    } catch (IOException ex) {
        Tools.showError(ex);
    }
}

From source file:org.languagetool.gui.Tools.java

private static File openFileDialog(Frame frame, FileFilter fileFilter, File initialDir, int mode) {
    JFileChooser jfc = new JFileChooser();
    jfc.setFileSelectionMode(mode);/*w  w w.ja  v  a  2 s .  c  om*/
    jfc.setCurrentDirectory(initialDir);
    jfc.setFileFilter(fileFilter);
    jfc.showOpenDialog(frame);
    return jfc.getSelectedFile();
}

From source file:org.n52.ifgicopter.spf.input.GpxInputPlugin.java

/**
 * /*from  w  w  w  .  j  a  v a  2  s  .  c om*/
 */
protected void selectGpxFileAction() {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            JFileChooser fc = new JFileChooser();
            fc.setDialogTitle("Select GPX File");
            fc.setFileFilter(new FileFilter() {

                @Override
                public boolean accept(File f) {
                    if (f.getName().toLowerCase().endsWith("gpx") || f.getName().toLowerCase().endsWith("xml"))
                        return true;
                    if (f.isDirectory())
                        return true;

                    return false;
                }

                @Override
                public String getDescription() {
                    return "GPX file";
                }
            });
            File gpxfile = new File(getGpxFilePath());
            if (gpxfile.isFile()) {
                fc.setCurrentDirectory(gpxfile.getParentFile());
            }

            int returnVal = fc.showOpenDialog(getUserInterface().getGui());

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                setGpxFilePath(file.getAbsolutePath());
            } else {
                getLog().debug("Open command cancelled by user.");
            }

            fc = null;
        }
    });
}

From source file:org.n52.ifgicopter.spf.output.GpxOutputPlugin.java

/**
 * /* w  ww. j  a va2s  .  c o  m*/
 */
protected void selectGpxFileAction() {
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            JFileChooser fc = new JFileChooser();
            fc.setDialogTitle("Select GPX File");
            fc.setFileFilter(new FileFilter() {

                @Override
                public boolean accept(File f) {
                    if (f.getName().toLowerCase().endsWith("gpx") || f.getName().toLowerCase().endsWith("xml"))
                        return true;
                    if (f.isDirectory())
                        return true;

                    return false;
                }

                @Override
                public String getDescription() {
                    return "GPX file";
                }
            });

            File gpxfile = new File(getGpxFilePath());
            if (gpxfile.isFile()) {
                fc.setCurrentDirectory(gpxfile.getParentFile());
            }

            int returnVal = fc.showOpenDialog(getUserInterface().getGui());

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                if (!file.getName().endsWith(".gpx") || !file.getName().endsWith(".xml"))
                    setGpxFilePath(file.getAbsolutePath() + ".gpx");
                else
                    setGpxFilePath(file.getAbsolutePath());
            } else {
                log.debug("Open command cancelled by user.");
            }

            fc = null;
        }
    });
}

From source file:org.n52.sos.importer.controller.Step1Controller.java

public void browseButtonClicked() {
    final JFileChooser fc = new JFileChooser();
    fc.setFileFilter(new CSVFileFilter());
    if (fc.showOpenDialog(getStepPanel()) == JFileChooser.APPROVE_OPTION) {
        step1Panel.setCSVFilePath(fc.getSelectedFile().getAbsolutePath());
        checkInputFileValue();//w  w w.  ja  v a2  s  . c om
    }
}

From source file:org.ohdsi.whiteRabbit.WhiteRabbitMain.java

private void pickTables() {
    DbSettings sourceDbSettings = getSourceDbSettings();
    if (sourceDbSettings != null) {
        if (sourceDbSettings.dataType == DbSettings.CSVFILES) {
            JFileChooser fileChooser = new JFileChooser(new File(folderField.getText()));
            fileChooser.setMultiSelectionEnabled(true);
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Delimited text files", "csv", "txt");
            fileChooser.setFileFilter(filter);

            int returnVal = fileChooser.showDialog(frame, "Select tables");
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                for (File table : fileChooser.getSelectedFiles()) {
                    String tableName = DirectoryUtilities.getRelativePath(new File(folderField.getText()),
                            table);//  w w  w.j av a 2  s.  c o m
                    if (!tables.contains(tableName))
                        tables.add(tableName);
                    tableList.setListData(tables);
                }

            }
        } else if (sourceDbSettings.dataType == DbSettings.DATABASE) {
            RichConnection connection = new RichConnection(sourceDbSettings.server, sourceDbSettings.domain,
                    sourceDbSettings.user, sourceDbSettings.password, sourceDbSettings.dbType);
            String tableNames = StringUtilities.join(connection.getTableNames(sourceDbSettings.database), "\t");
            if (tableNames.length() == 0) {
                JOptionPane.showMessageDialog(frame, "No tables found in database " + sourceDbSettings.database,
                        "Error fetching table names", JOptionPane.ERROR_MESSAGE);
            } else {
                DBTableSelectionDialog selectionDialog = new DBTableSelectionDialog(frame, true, tableNames);
                if (selectionDialog.getAnswer()) {
                    for (Object item : selectionDialog.getSelectedItems()) {
                        if (!tables.contains(item))
                            tables.add((String) item);
                        tableList.setListData(tables);
                    }
                }
            }
            connection.close();
        }
    }
}

From source file:org.omelogic.tome.EpiTome.java

public void init() {
    backingGraph = null;//from w  ww  .j a  v  a2 s. c  o m
    tomeGraph = null;
    idFilter = null;

    JPanel tablePanel = new JPanel();
    tomeTable = new JTable();
    JScrollPane tomeTableScroller = new JScrollPane(tomeTable);
    tablePanel.setLayout(new BoxLayout(tablePanel, BoxLayout.PAGE_AXIS));
    tablePanel.add(tomeTableScroller);
    tomeProps = new JLabel("");

    JPanel tomePropsPanel = new JPanel(new BorderLayout());
    tomePropsPanel.add(tomeProps, BorderLayout.LINE_START);
    //tablePanel.add(tomeTableFixed);
    tablePanel.add(tomePropsPanel);
    //JScrollPane tablePanelScroller = new JScrollPane(tablePanel);
    tablePanel.setPreferredSize(new Dimension(300, 400));

    //####### CONTROLS #########################################
    JPanel controlPanel = new JPanel();
    JButton load = new JButton("LOAD");
    load.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent act) {
            JFileChooser chooser = new JFileChooser();
            chooser.setFileFilter(new SIFFileFilter());
            chooser.setMultiSelectionEnabled(false);
            int returnVal = chooser.showOpenDialog(tomeFrame);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
            } else {
                return;
            }
            File sifFile = chooser.getSelectedFile();
            UndirectedSparseGraph result = null;
            try {
                result = SIFHandler.load(sifFile);
            } catch (Exception e) {
                System.out.println(e.toString());
            }
            System.out.println("Loaded file!");
            backingGraph = result;
            FilterDialog filterMe = new FilterDialog();
            idFilter = filterMe.getFilter();
            loadInitialGraph((UndirectedSparseGraph) TomeGraphUtilities.filterGraph(backingGraph, idFilter));

        }
    });

    JButton save = new JButton("SAVE");
    save.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent act) {
            if (tomeGraph == null) {
                JOptionPane.showMessageDialog(null, "No graph is loaded!", "ERROR!", JOptionPane.ERROR_MESSAGE);
                return;
            }
            JFileChooser chooser = new JFileChooser();
            if (((Double) ((HashMap<String, Double>) (tomeGraph.getUserDatum("GraphStatistics")))
                    .get("AveragePathLength")).isInfinite()) {
                JOptionPane.showMessageDialog(null,
                        "Graph is not fully connected! This renders most output useless. Try trimming the graph first...",
                        "ERROR!", JOptionPane.ERROR_MESSAGE);
                return;
            }

            int returnVal = chooser.showSaveDialog(EpiTome.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();

                FileOutputStream out; // declare a file output object
                PrintStream p; // declare a print stream object

                try {
                    // Create a new file output stream
                    out = new FileOutputStream(file);

                    // Connect print stream to the output stream
                    p = new PrintStream(out);

                    HashMap<String, Double> graphProps = (HashMap<String, Double>) tomeGraph
                            .getUserDatum("GraphStatistics");

                    p.println("#---SUMMARY---");
                    p.println("#NumNodes:\t" + tomeGraph.numVertices());
                    p.println("#NumEdges:\t" + tomeGraph.numEdges());
                    p.println("#ClustCoeff:\t" + graphProps.get(TomeGraphUtilities.CLUSTERING_COEFFICIENT));
                    p.println("#AvgPathLen:\t" + graphProps.get(TomeGraphUtilities.AVERAGE_PATH_LENGTH));
                    p.println("#AvgDegree:\t" + graphProps.get(TomeGraphUtilities.AVERAGE_DEGREE));
                    p.println("#-------------");
                    p.println("\n\n");

                    p.println("NodeID\tClustCoeff\tAvgPathLen\tAvgDegree");
                    Iterator<TomeVertex> vertIter = tomeGraph.getVertices().iterator();
                    while (vertIter.hasNext()) {
                        TomeVertex vert = vertIter.next();
                        p.println(vert.getID() + "\t" + vert.getClusteringCoefficient() + "\t"
                                + vert.getAverageDistance() + "\t" + vert.getDegree());
                    }

                    p.close();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Error writing to file!\n" + e.toString(), "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    });

    JButton trim = new JButton("TRIM");
    trim.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (tomeGraph == null) {
                JOptionPane.showMessageDialog(null, "No graph is loaded!", "ERROR!", JOptionPane.ERROR_MESSAGE);
                return;
            }
            TrimDialog trimMe = new TrimDialog();
            loadSubGraph(trimMe.getTrimmedGraph(tomeGraph));

        }
    });

    JButton rset = new JButton("RSET");
    rset.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (backingGraph == null) {
                JOptionPane.showMessageDialog(null, "No graph is loaded!", "ERROR!", JOptionPane.ERROR_MESSAGE);
                return;
            }
            loadInitialGraph((UndirectedSparseGraph) TomeGraphUtilities.filterGraph(backingGraph, idFilter));
        }
    });

    JButton view = new JButton("VIEW");
    view.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            if (tomeGraph == null) {
                JOptionPane.showMessageDialog(null, "No graph is loaded!", "ERROR!", JOptionPane.ERROR_MESSAGE);
                return;
            }
            GraphDialog graf = new GraphDialog(tomeGraph, getSelectedNodeSubGraph());
        }
    });

    JButton ctrl = new JButton("CTRL");
    ctrl.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (tomeGraph == null) {
                JOptionPane.showMessageDialog(null, "No graph is loaded!", "ERROR!", JOptionPane.ERROR_MESSAGE);
                return;
            }
            try {
                ControlsDialog ctrls = new ControlsDialog(tomeGraph, backingGraph, NUM_CONTROLS, NUM_BINS_MAX);
            } catch (Exception excep) {
            }
        }
    });

    JButton help = new JButton("HELP");
    help.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            HelpDialog.display();
        }
    });

    controlPanel.add(load);
    controlPanel.add(save);
    controlPanel.add(trim);
    controlPanel.add(rset);
    controlPanel.add(view);
    controlPanel.add(ctrl);
    controlPanel.add(help);

    //##########################################################

    Container content = tomeFrame.getContentPane();

    content.removeAll();
    content.add(tablePanel, BorderLayout.CENTER);
    content.add(controlPanel, BorderLayout.SOUTH);

}

From source file:org.owasp.jbrofuzz.fuzz.io.OpenSession.java

License:asdf

public OpenSession(JBroFuzzWindow mWindow, String fileName) {
    this.mWindow = mWindow;
    //   JBroFuzzPrefs prefs = new JBroFuzzPrefs();
    File file = null;/*from ww  w.  jav a 2  s. c  om*/
    // Set the Fuzzing Panel as the one to view
    mWindow.setTabShow(JBroFuzzWindow.ID_PANEL_FUZZING);

    final JBroFuzzFileFilter filter = new JBroFuzzFileFilter();
    final String dirString = JBroFuzz.PREFS.get(JBroFuzzPrefs.DIRS[2].getId(), System.getProperty("user.dir"));

    JFileChooser fc = new JFileChooser();

    if ((fileName.length() == 0 || fileName.equals(""))
            && (!JBroFuzzPrefs.DBSETTINGS[11].getId().equals("SQLite")
                    && !JBroFuzzPrefs.DBSETTINGS[11].getId().equals("CouchDB"))) {
        try {
            if ((new File(dirString).isDirectory())) {
                fc = new JFileChooser(dirString);
            } else {
                fc = new JFileChooser();
            }
        } catch (final SecurityException e1) {
            fc = new JFileChooser();
            Logger.log("A security exception occured, while attempting to point to a directory", 4);
        }

        fc.setFileFilter(filter);

        final int returnVal = fc.showOpenDialog(mWindow);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = fc.getSelectedFile();
            setUpFromFile(file, fc);
        }
    } else if ((fileName.length() > 0 && !fileName.equals(""))) {
        file = new File(fileName);
        setUpFromFile(file, fc);
    }
}