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.owasp.jbrofuzz.fuzz.io.Save.java

/**
 * <p>Method for obtaining a file location, through a 
 * JFileChooser for the user to save a .jbrofuzz file.</p>
 * /*from  w ww  .  java 2 s  .  com*/
 * <p>In the event of an error or an exception, this
 * method returns null.</p>
 * 
 * @param mWindow
 * @return
 */
public static File showSaveDialog(JBroFuzzWindow mWindow) {

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

    final File dirLocation = new File(dirString);
    JFileChooser fChooser;
    try {
        if (dirLocation.exists() && dirLocation.isDirectory()) {
            fChooser = new JFileChooser(dirString);
        } else {
            fChooser = new JFileChooser();
        }
    } catch (final SecurityException sException) {
        fChooser = new JFileChooser();
        Logger.log("A security exception occured, while attempting to save as to a directory", 4);
    }
    // Set the filter for the file extension
    fChooser.setFileFilter(new JBroFuzzFileFilter());
    // Talk to the user
    final int retValue = fChooser.showSaveDialog(mWindow);
    // If there is an approval or selection
    if (retValue == JFileChooser.APPROVE_OPTION) {

        File returnFile = fChooser.getSelectedFile();
        Logger.log("Saving: " + returnFile.getName(), 1);
        // 
        final String filePath = returnFile.getAbsolutePath().toLowerCase();
        if (!filePath.endsWith(".jbrofuzz")) {
            returnFile = new File(filePath + ".jbrofuzz");
        }

        if (returnFile.exists()) {

            final int overwrite = JOptionPane.showConfirmDialog(fChooser,
                    "File already exists. Do you \nwant to replace it?", " JBroFuzz - Save ",
                    JOptionPane.YES_NO_OPTION);

            // If the user does not want to overwrite, return null
            if (overwrite == JOptionPane.NO_OPTION) {
                return null;
            }
        }
        // Before returning the file, set the preference
        // for the parent directory
        final String parentDir = returnFile.getParent();
        if (parentDir != null) {
            JBroFuzz.PREFS.put(JBroFuzzPrefs.DIRS[2].getId(), parentDir);
        }

        return returnFile;
    }

    // If the user cancelled, return nulls
    return null;

}

From source file:org.parosproxy.paros.control.MenuFileControl.java

private void openFileBasedSession() {
    JFileChooser chooser = new JFileChooser(model.getOptionsParam().getUserDirectory());
    chooser.setFileHidingEnabled(false); // By default ZAP on linux puts timestamped sessions under a 'dot' directory 
    File file = null;/*from www . j a  v  a  2s  . c o m*/
    chooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else if (file.isFile() && file.getName().endsWith(".session")) {
                return true;
            }
            return false;
        }

        @Override
        public String getDescription() {
            // ZAP: Rebrand
            return Constant.messages.getString("file.format.zap.session");
        }
    });
    int rc = chooser.showOpenDialog(view.getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        try {
            file = chooser.getSelectedFile();
            if (file == null) {
                return;
            }
            model.getOptionsParam().setUserDirectory(chooser.getCurrentDirectory());
            log.info("opening session file " + file.getAbsolutePath());
            waitMessageDialog = view.getWaitMessageDialog(Constant.messages.getString("menu.file.loadSession"));
            control.openSession(file, this);
            waitMessageDialog.setVisible(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}

From source file:org.parosproxy.paros.control.MenuFileControl.java

public void saveAsSession() {
    if (!informStopActiveActions()) {
        return;//from   w ww .  j a va 2s .  c o m
    }

    Session session = model.getSession();

    JFileChooser chooser = new JFileChooser(model.getOptionsParam().getUserDirectory());
    // ZAP: set session name as file name proposal
    File fileproposal = new File(session.getSessionName());
    if (session.getFileName() != null && session.getFileName().trim().length() > 0) {
        // if there is already a file name, use it
        fileproposal = new File(session.getFileName());
    }
    chooser.setSelectedFile(fileproposal);
    chooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else if (file.isFile() && file.getName().endsWith(".session")) {
                return true;
            }
            return false;
        }

        @Override
        public String getDescription() {
            // ZAP: Rebrand
            return Constant.messages.getString("file.format.zap.session");
        }
    });
    File file = null;
    int rc = chooser.showSaveDialog(view.getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        if (file == null) {
            return;
        }
        model.getOptionsParam().setUserDirectory(chooser.getCurrentDirectory());
        String fileName = file.getAbsolutePath();
        if (!fileName.endsWith(".session")) {
            fileName += ".session";
        }

        try {
            waitMessageDialog = view
                    .getWaitMessageDialog(Constant.messages.getString("menu.file.savingSession")); // ZAP: i18n
            control.saveSession(fileName, this);
            log.info("save as session file " + session.getFileName());
            waitMessageDialog.setVisible(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}

From source file:org.parosproxy.paros.control.MenuFileControl.java

public void saveSnapshot() {
    String activeActions = wrapEntriesInLiTags(control.getExtensionLoader().getActiveActions());
    if (!activeActions.isEmpty()) {
        view.showMessageDialog(Constant.messages.getString("menu.file.snapshot.activeactions", activeActions));
        return;//w  ww. j  a  v  a 2 s.  c  om
    }

    Session session = model.getSession();

    JFileChooser chooser = new JFileChooser(model.getOptionsParam().getUserDirectory());
    // ZAP: set session name as file name proposal
    File fileproposal = new File(session.getSessionName());
    if (session.getFileName() != null && session.getFileName().trim().length() > 0) {
        String proposedFileName;
        // if there is already a file name, use it and add a timestamp
        proposedFileName = StringUtils.removeEnd(session.getFileName(), ".session");
        proposedFileName += "-" + dateFormat.format(new Date()) + ".session";
        fileproposal = new File(proposedFileName);
    }
    chooser.setSelectedFile(fileproposal);
    chooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else if (file.isFile() && file.getName().endsWith(".session")) {
                return true;
            }
            return false;
        }

        @Override
        public String getDescription() {
            return Constant.messages.getString("file.format.zap.session");
        }
    });
    File file = null;
    int rc = chooser.showSaveDialog(view.getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        if (file == null) {
            return;
        }
        model.getOptionsParam().setUserDirectory(chooser.getCurrentDirectory());
        String fileName = file.getAbsolutePath();
        if (!fileName.endsWith(".session")) {
            fileName += ".session";
        }

        try {
            waitMessageDialog = view
                    .getWaitMessageDialog(Constant.messages.getString("menu.file.savingSnapshot")); // ZAP: i18n
            control.snapshotSession(fileName, this);
            log.info("Snapshotting: " + session.getFileName() + " as " + fileName);
            waitMessageDialog.setVisible(true);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}

From source file:org.parosproxy.paros.control.MenuFileControl.java

/**
 * Prompt the user to export a context//from  w  w  w . jav  a 2  s  .  co m
 */
public void importContext() {
    JFileChooser chooser = new JFileChooser(Constant.getContextsDir());
    File file = null;
    chooser.setFileFilter(new FileFilter() {
        @Override
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else if (file.isFile() && file.getName().endsWith(".context")) {
                return true;
            }
            return false;
        }

        @Override
        public String getDescription() {
            return Constant.messages.getString("file.format.zap.context");
        }
    });

    int rc = chooser.showOpenDialog(View.getSingleton().getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        try {
            file = chooser.getSelectedFile();
            if (file == null || !file.exists()) {
                return;
            }
            // Import the context
            Model.getSingleton().getSession().importContext(file);

            // Show the dialog
            View.getSingleton().showSessionDialog(Model.getSingleton().getSession(),
                    Constant.messages.getString("context.list"), true);

        } catch (IllegalContextNameException e) {
            String detailError;
            if (e.getReason() == IllegalContextNameException.Reason.EMPTY_NAME) {
                detailError = Constant.messages.getString("context.error.name.empty");
            } else if (e.getReason() == IllegalContextNameException.Reason.DUPLICATED_NAME) {
                detailError = Constant.messages.getString("context.error.name.duplicated");
            } else {
                detailError = Constant.messages.getString("context.error.name.unknown");
            }
            View.getSingleton()
                    .showWarningDialog(Constant.messages.getString("context.import.error", detailError));
        } catch (Exception e1) {
            log.debug(e1.getMessage(), e1);
            View.getSingleton()
                    .showWarningDialog(Constant.messages.getString("context.import.error", e1.getMessage()));
        }
    }
}

From source file:org.parosproxy.paros.extension.history.PopupMenuExportMessage.java

private File getOutputFile() {

    JFileChooser chooser = new JFileChooser(extension.getModel().getOptionsParam().getUserDirectory());
    chooser.setFileFilter(new FileFilter() {
        public boolean accept(File file) {
            if (file.isDirectory()) {
                return true;
            } else if (file.isFile() && file.getName().endsWith(".txt")) {
                return true;
            }/*from   w w  w  . ja va 2s.com*/
            return false;
        }

        public String getDescription() {
            return "ASCII text file";
        }
    });
    File file = null;
    int rc = chooser.showSaveDialog(extension.getView().getMainFrame());
    if (rc == JFileChooser.APPROVE_OPTION) {
        file = chooser.getSelectedFile();
        if (file == null) {
            return file;
        }
        extension.getModel().getOptionsParam().setUserDirectory(chooser.getCurrentDirectory());
        String fileName = file.getAbsolutePath();
        if (!fileName.endsWith(".txt")) {
            fileName += ".txt";
            file = new File(fileName);
        }
        return file;

    }
    return file;
}

From source file:org.pmedv.blackboard.commands.CreatePartListCommand.java

@Override
public void execute(ActionEvent e) {
    ApplicationContext ctx = AppContext.getContext();
    final ApplicationWindow win = ctx.getBean(ApplicationWindow.class);
    final BoardEditor editor = EditorUtils.getCurrentActiveEditor();
    StringBuffer partList = new StringBuffer();
    partList.append("Name,Value,Package\n");
    for (Layer layer : editor.getModel().getLayers()) {
        for (Item i : layer.getItems()) {
            if (i instanceof Part && !(i instanceof TextPart)) {
                Part p = (Part) i;/*from  ww w  .  ja v  a 2  s . c o m*/
                partList.append(p.getName() + "," + p.getValue() + "," + p.getPackageType() + "\n");
            }
            if (i instanceof Resistor) {
                Resistor r = (Resistor) i;
                partList.append(r.getName() + "," + r.getValue() + " Ohm,RESISTOR\n");
            }
        }
    }
    final JFileChooser fc = new JFileChooser(".");
    fc.setFileFilter(new CSVFilter());
    fc.setDialogTitle(resources.getResourceByKey("CreatePartListCommand.dialog.subtitle"));
    fc.setApproveButtonText(resources.getResourceByKey("msg.save"));
    int result = fc.showOpenDialog(win);
    if (result == JFileChooser.APPROVE_OPTION) {
        if (fc.getSelectedFile() == null)
            return;
        File selectedFile = fc.getSelectedFile();
        if (selectedFile != null) {
            // if csv extension is missing...
            if (!selectedFile.getName().endsWith(".csv")) {
                selectedFile = new File(selectedFile.getAbsolutePath() + ".csv");
            }
            try {
                FileUtils.writeStringToFile(selectedFile, partList.toString(), "UTF-8");
                int res = JOptionPane.showConfirmDialog(win, resources.getResourceByKey("msg.viewpartlist"),
                        resources.getResourceByKey("msg.question"), JOptionPane.YES_NO_OPTION);
                if (res == JOptionPane.YES_OPTION) {
                    JTextArea textPane = new JTextArea();
                    textPane.setText(partList.toString());
                    JScrollPane s = new JScrollPane(textPane);
                    s.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
                    s.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                    View v = new View("Partlist for " + editor.getCurrentFile().getName(), null, s);
                    editor.setView(v);
                    final ImageIcon icon = resources.getIcon("icon.document.html");
                    v.getViewProperties().setIcon(icon);
                    v.getViewProperties().setTitle("Partlist for " + editor.getCurrentFile().getName());
                    openEditor(v, editor.getCurrentFile().hashCode());
                    v.undock(new Point(20, 10));
                }
            } catch (IOException e1) {
                ErrorUtils.showErrorDialog(e1);
            }
        }
    }
}

From source file:org.pmedv.blackboard.commands.OpenBoardCommand.java

@Override
public void execute(ActionEvent e) {

    final ApplicationWindow win = ctx.getBean(ApplicationWindow.class);

    // No file selected before, popup a dialog and query the user which file to open.
    if (file == null) {
        String path = System.getProperty("user.home");
        if (AppContext.getLastSelectedFolder() != null) {
            path = AppContext.getLastSelectedFolder();
        }/*w w  w  .  j a  v a  2  s. c  om*/
        JFileChooser fc = new JFileChooser(path);
        fc.setDialogTitle(resources.getResourceByKey("OpenBoardCommand.name"));
        fc.setFileFilter(new FefaultFileFilter());
        int result = fc.showOpenDialog(win);
        if (result == JFileChooser.APPROVE_OPTION) {
            if (fc.getSelectedFile() == null)
                return;
            file = fc.getSelectedFile();
            AppContext.setLastSelectedFolder(file.getParentFile().getAbsolutePath());
        } else {
            return;
        }
    }

    final JWindow topWindow = new JWindow();
    topWindow.setSize(390, 50);
    topWindow.setLayout(new BorderLayout());
    topWindow.setBackground(Color.WHITE);

    final JPanel content = new JPanel(new BorderLayout());
    content.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK),
            BorderFactory.createEmptyBorder(10, 10, 10, 10)));
    content.setBackground(Color.WHITE);
    final JLabel infoLabel = new JLabel(
            resources.getResourceByKey("OpenBoardCommand.waitMsg") + " " + file.getName());
    infoLabel.setVerticalAlignment(SwingConstants.CENTER);
    content.add(infoLabel, BorderLayout.SOUTH);

    final JBusyComponent<JPanel> busyPanel = new JBusyComponent<JPanel>(content);
    busyPanel.setBusy(true);

    topWindow.getContentPane().add(busyPanel, BorderLayout.CENTER);
    topWindow.setLocationRelativeTo(null);
    topWindow.add(busyPanel, BorderLayout.CENTER);

    final SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>() {

        @Override
        protected Boolean doInBackground() {
            topWindow.setVisible(true);
            doOpen();
            return Boolean.valueOf(true);
        }

        @Override
        protected void done() {
            topWindow.setVisible(false);
            topWindow.dispose();
            for (Runnable r : postConfigurators) {
                SwingUtilities.invokeLater(r);
            }
        }
    };

    worker.execute();

}

From source file:org.processmining.analysis.performance.PerformanceAnalysisGUI.java

/**
 * Creates a filechooser where the user can select the (comma-seperated)
 * file that he wants to export to. If this file already exists, permission
 * to overwrite is requested, else a new file is created to which the
 * time-metrics of the selected place/transitions are exported.
 * /* ww w.  java  2  s.co  m*/
 */
private void exportObjectMetrics() {
    // create and initialize the file chooser
    final JFileChooser fc = new JFileChooser();
    NameFilter filt1 = new NameFilter(".csv");
    NameFilter filt2 = new NameFilter(".txt");
    fc.addChoosableFileFilter(filt1);
    fc.addChoosableFileFilter(filt2);
    fc.setAcceptAllFileFilterUsed(false);
    fc.setFileFilter(filt1);
    // check whether a place is selected
    int result = fc.showDialog(this, "Export");
    if (result == 0) {
        // Export-button was pushed
        File selectedFile = fc.getSelectedFile();
        if (!(selectedFile.getName().endsWith(fc.getFileFilter().getDescription().substring(1)))) {
            // create new file, with filetype added to it
            selectedFile = new File(
                    selectedFile.getAbsolutePath() + fc.getFileFilter().getDescription().substring(1));
        }

        if (!selectedFile.exists()) {
            if (boxMap.get(sb1.getSelectedItem()) instanceof ExtendedPlace) {
                // actually perform export of place time-metrics
                exportPlaceMetrics(selectedFile);
            } else {
                if (boxMap.get(sb2.getSelectedItem()) instanceof ExtendedTransition) {
                    // actually perform export of transition time-metrics
                    exportTransitionMetrics(selectedFile);
                } else {
                    // actually perform export of activity time-metrics
                    exportActivityMetrics(selectedFile);
                }
            }
        } else {
            // file already exist, open a confirm dialog containing a
            // 'Yes' Button as well as a 'No' button
            int overwrite = JOptionPane.showConfirmDialog(this, "File already exists! Overwrite?",
                    "Confirm Dialog", 0);
            if (overwrite == 0) {
                // user has selected Yes
                if (boxMap.get(sb1.getSelectedItem()) instanceof ExtendedPlace) {
                    // actually perform export of place time-metrics
                    exportPlaceMetrics(selectedFile);
                } else {
                    if (boxMap.get(sb2.getSelectedItem()) instanceof ExtendedTransition) {
                        // actually perform export of transition
                        // time-metrics
                        exportTransitionMetrics(selectedFile);
                    } else {
                        // actually perform export of activity time-metrics
                        exportActivityMetrics(selectedFile);
                    }
                }
            }
        }
    }
}

From source file:org.processmining.analysis.performance.PerformanceAnalysisGUI.java

/**
 * Creates a filechooser where the user can select the (comma-seperated)
 * file that he wants to export to. If this file already exists, permission
 * to overwrite is requested, else a new file is created to which the
 * throughput times of the selected process instances are exported.
 * // ww  w . j a  v  a  2 s  .co m
 */
private void exportProcessMetrics() {
    // create and initialize the file chooser
    final JFileChooser fc = new JFileChooser();
    NameFilter filt1 = new NameFilter(".csv");
    NameFilter filt2 = new NameFilter(".txt");
    fc.addChoosableFileFilter(filt1);
    fc.addChoosableFileFilter(filt2);
    fc.setAcceptAllFileFilterUsed(false);
    fc.setFileFilter(filt1);
    // check whether a place is selected
    int result = fc.showDialog(this, "Export");
    if (result == 0) {
        // Export-button was pushed
        File selectedFile = fc.getSelectedFile();
        if (!(selectedFile.getName().endsWith(fc.getFileFilter().getDescription().substring(1)))) {
            // create new file, with filetype added to it
            selectedFile = new File(
                    selectedFile.getAbsolutePath() + fc.getFileFilter().getDescription().substring(1));
        }
        if (!selectedFile.exists()) {
            try {
                // actually export the throughput times to the file
                replayResult.exportToFile(getSelectedInstances(), selectedFile, timeDivider, timeSort,
                        advancedSettings[0]);
            } catch (IOException ex) {
                Message.add("IO exception: " + ex.toString(), 2);
            }
        } else {
            // file already exist, open a confirm dialog containing a
            // 'Yes' Button as well as a 'No' button
            int overwrite = JOptionPane.showConfirmDialog(this, "File already exists! Overwrite?",
                    "Confirm Dialog", 0);
            if (overwrite == 0) {
                // user has selected Yes
                try {
                    // actually export the throughput times to the file
                    replayResult.exportToFile(getSelectedInstances(), selectedFile, timeDivider, timeSort,
                            advancedSettings[0]);
                } catch (IOException ex) {
                    Message.add("IO exception: " + ex.toString(), 2);
                }
            }
        }
    }
}