Example usage for javax.swing JFileChooser addChoosableFileFilter

List of usage examples for javax.swing JFileChooser addChoosableFileFilter

Introduction

In this page you can find the example usage for javax.swing JFileChooser addChoosableFileFilter.

Prototype

@BeanProperty(preferred = true, description = "Adds a filter to the list of user choosable file filters.")
public void addChoosableFileFilter(FileFilter filter) 

Source Link

Document

Adds a filter to the list of user choosable file filters.

Usage

From source file:org.apache.cayenne.modeler.graph.action.SaveAsImageAction.java

@Override
public void performAction(ActionEvent e) {
    // find start directory in preferences
    FSPath lastDir = getApplication().getFrameController().getLastDirectory();

    // configure dialog
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    lastDir.updateChooser(chooser);//from www.  j  a  v  a  2s  .com

    chooser.setAcceptAllFileFilterUsed(false);

    String ext = "png";
    chooser.addChoosableFileFilter(FileFilters.getExtensionFileFilter(ext, "PNG Images"));

    int status = chooser.showSaveDialog(Application.getFrame());
    if (status == JFileChooser.APPROVE_OPTION) {
        lastDir.updateFromChooser(chooser);

        String path = chooser.getSelectedFile().getPath();
        if (!path.endsWith("." + ext)) {
            path += "." + ext;
        }

        try {

            JGraph graph = dataDomainGraphTab.getGraph();
            BufferedImage img = graph.getImage(null, 0);

            try (OutputStream out = new FileOutputStream(path);) {
                ImageIO.write(img, ext, out);
                out.flush();
            }

        } catch (IOException ex) {
            logObj.error("Could not save image", ex);
            JOptionPane.showMessageDialog(Application.getFrame(), "Could not save image.", "Error saving image",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:org.colombbus.tangara.CommandSelection.java

private JFileChooser createFileChooser() {
    String title;/*from www .  j  a  va 2s  . c  o m*/
    FileFilter fileFilter;
    if (mode == MODE_PROGRAM_CREATION) {
        title = Messages.getString("CommandSelection.programCreation.save.title");
        fileFilter = createTangaraFileFilter();
    } else {
        title = Messages.getString("CommandSelection.fileCreation.save.title");
        fileFilter = createTextFileFilter();
    }

    JFileChooser fileChooser = new JFileChooser(myParent.getCurrentDirectory());
    fileChooser.setDialogTitle(title);
    fileChooser.addChoosableFileFilter(fileFilter);
    return fileChooser;
}

From source file:org.drools.mas.SimpleClient.java

private void menuSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuSaveAsActionPerformed
    JFileChooser saveFileChooser = new JFileChooser();
    saveFileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Model File", "mod"));
    int showDialog = saveFileChooser.showDialog(this, "Save");
    if (showDialog == JFileChooser.APPROVE_OPTION) {
        try {//w  ww. j a v a 2s. c  o  m
            File selectedFile = saveFileChooser.getSelectedFile();
            if (selectedFile.exists()) {
                int showConfirmDialog = JOptionPane.showConfirmDialog(this, "The file '"
                        + selectedFile.getCanonicalPath() + "' already exstits. Do you want to continue?");
                if (showConfirmDialog != JOptionPane.OK_OPTION) {
                    return;
                }
            }

            if (!selectedFile.getName().endsWith(".mod")) {
                selectedFile = new File(selectedFile.getAbsolutePath() + ".mod");
            }

            String content = ObjectSerializerFactory.getObjectSerializerInstance()
                    .serialize(this.factTableModel.getFacts());
            IOUtils.copy(new ByteArrayInputStream(content.getBytes()), new FileOutputStream(selectedFile));
            JOptionPane.showMessageDialog(this, "File Saved!");

            this.setTitle(selectedFile.getName());

        } catch (Exception ex) {
            Logger.getLogger(SimpleClient.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, "Error saving file: " + ex.getMessage(), "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:org.drools.mas.SimpleClient.java

private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
    JFileChooser openFileChooser = new JFileChooser();
    openFileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Model File", "mod"));

    int showDialog = openFileChooser.showDialog(this, "Open");
    if (showDialog == JFileChooser.APPROVE_OPTION) {
        try {//w  ww .ja va2  s  .com
            File selectedFile = openFileChooser.getSelectedFile();
            if (!selectedFile.exists()) {
                JOptionPane.showMessageDialog(this, "File: " + selectedFile.getCanonicalPath(), "Error",
                        JOptionPane.ERROR_MESSAGE);
                return;
            }

            String toString = IOUtils.toString(new FileInputStream(selectedFile));

            List facts = (List) ObjectSerializerFactory.getObjectSerializerInstance().deserialize(toString);

            this.factTableModel.clear();
            for (Object fact : facts) {
                this.factTableModel.addFact(fact);
            }

            this.factTableModel.fireTableDataChanged();

            this.setTitle(selectedFile.getName());
        } catch (Exception ex) {
            Logger.getLogger(SimpleClient.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(this, "Error opening file: " + ex.getMessage(), "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:org.fhaes.gui.ShapeFileDialog.java

/**
 * Prompt the user for an output filename
 * /*  w w  w .j a  va 2s.c  o m*/
 * @param filter
 * @return
 */
private File getOutputFile(FileFilter filter) {

    String lastVisitedFolder = App.prefs.getPref(PrefKey.PREF_LAST_EXPORT_FOLDER, null);
    File outputFile;

    // Create a file chooser
    final JFileChooser fc = new JFileChooser(lastVisitedFolder);

    fc.setAcceptAllFileFilterUsed(true);

    if (filter != null) {
        fc.addChoosableFileFilter(filter);
        fc.setFileFilter(filter);
    }

    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setMultiSelectionEnabled(false);
    fc.setDialogTitle("Save as...");

    // In response to a button click:
    int returnVal = fc.showSaveDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        outputFile = fc.getSelectedFile();

        if (FileUtils.getExtension(outputFile.getAbsolutePath()) == "") {
            log.debug("Output file extension not set by user");

            if (fc.getFileFilter().getDescription().equals(new SHPFileFilter().getDescription())) {
                log.debug("Adding shp extension to output file name");
                outputFile = new File(outputFile.getAbsolutePath() + ".shp");
            }
        } else {
            log.debug("Output file extension set my user to '"
                    + FileUtils.getExtension(outputFile.getAbsolutePath()) + "'");
        }

        App.prefs.setPref(PrefKey.PREF_LAST_EXPORT_FOLDER, outputFile.getAbsolutePath());
    } else {
        return null;
    }

    if (outputFile.exists()) {
        Object[] options = { "Overwrite", "No", "Cancel" };
        int response = JOptionPane.showOptionDialog(this,
                "The file '" + outputFile.getName() + "' already exists.  Are you sure you want to overwrite?",
                "Confirm", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, // do not use a custom Icon
                options, // the titles of buttons
                options[0]); // default button title

        if (response != JOptionPane.YES_OPTION) {
            return null;
        }
    }

    return outputFile;
}

From source file:org.freeplane.features.url.mindmapmode.ExportBranchAction.java

public void actionPerformed(final ActionEvent e) {
    final NodeModel existingNode = Controller.getCurrentModeController().getMapController().getSelectedNode();
    final Controller controller = Controller.getCurrentController();
    final MapModel parentMap = controller.getMap();
    if (parentMap == null || existingNode == null || existingNode.isRoot()) {
        controller.getViewController().err("Could not export branch.");
        return;/*  w w  w  . ja va  2 s. com*/
    }
    if (parentMap.getFile() == null) {
        controller.getViewController().out("You must save the current map first!");
        ((MModeController) Controller.getCurrentModeController()).save();
    }
    JFileChooser chooser;
    final File file = parentMap.getFile();
    if (file == null) {
        return;
    }
    chooser = new JFileChooser(file.getParentFile());
    chooser.setSelectedFile(
            new File(createFileName(TextController.getController().getShortText(existingNode))));
    if (((MFileManager) UrlManager.getController()).getFileFilter() != null) {
        chooser.addChoosableFileFilter(((MFileManager) UrlManager.getController()).getFileFilter());
    }
    final int returnVal = chooser.showSaveDialog(controller.getViewController().getContentPane());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File chosenFile = chooser.getSelectedFile();
        final String ext = FileUtils.getExtension(chosenFile.getName());
        if (!ext.equals(org.freeplane.features.url.UrlManager.FREEPLANE_FILE_EXTENSION_WITHOUT_DOT)) {
            chosenFile = new File(chosenFile.getParent(),
                    chosenFile.getName() + org.freeplane.features.url.UrlManager.FREEPLANE_FILE_EXTENSION);
        }
        try {
            Compat.fileToUrl(chosenFile);
        } catch (final MalformedURLException ex) {
            UITools.errorMessage(TextUtils.getText("invalid_url"));
            return;
        }
        if (chosenFile.exists()) {
            final int overwriteMap = JOptionPane.showConfirmDialog(
                    controller.getMapViewManager().getMapViewComponent(),
                    TextUtils.getText("map_already_exists"), "Freeplane", JOptionPane.YES_NO_OPTION);
            if (overwriteMap != JOptionPane.YES_OPTION) {
                return;
            }
        }
        /*
         * Now make a copy from the node, remove the node from the map and
         * create a new Map with the node as root, store the new Map, add
         * the copy of the node to the parent, and set a link from the copy
         * to the new Map.
         */
        final NodeModel parent = existingNode.getParentNode();
        final File oldFile = parentMap.getFile();

        final URI newUri = LinkController.toLinkTypeDependantURI(oldFile, chosenFile);
        final URI oldUri = LinkController.toLinkTypeDependantURI(chosenFile, file);
        ((MLinkController) LinkController.getController()).setLink(existingNode, oldUri,
                LinkController.LINK_ABSOLUTE);
        final int nodePosition = parent.getChildPosition(existingNode);
        final ModeController modeController = Controller.getCurrentModeController();
        modeController.undoableResolveParentExtensions(LogicalStyleKeys.NODE_STYLE, existingNode);
        final MMapController mMapController = (MMapController) modeController.getMapController();
        mMapController.deleteNode(existingNode);
        {
            final IActor actor = new IActor() {
                private final boolean wasFolded = existingNode.isFolded();

                public void undo() {
                    PersistentNodeHook.removeMapExtensions(existingNode);
                    existingNode.setMap(parentMap);
                    existingNode.setFolded(wasFolded);
                }

                public String getDescription() {
                    return "ExportBranchAction";
                }

                public void act() {
                    existingNode.setParent(null);
                    existingNode.setFolded(false);
                    mMapController.newModel(existingNode);
                }
            };
            Controller.getCurrentModeController().execute(actor, parentMap);
        }
        final MapModel map = existingNode.getMap();
        IExtension[] oldExtensions = map.getRootNode().getSharedExtensions().values()
                .toArray(new IExtension[] {});
        for (final IExtension extension : oldExtensions) {
            final Class<? extends IExtension> clazz = extension.getClass();
            if (PersistentNodeHook.isMapExtension(clazz)) {
                existingNode.removeExtension(clazz);
            }
        }
        final Collection<IExtension> newExtensions = parentMap.getRootNode().getSharedExtensions().values();
        for (final IExtension extension : newExtensions) {
            final Class<? extends IExtension> clazz = extension.getClass();
            if (PersistentNodeHook.isMapExtension(clazz)) {
                existingNode.addExtension(extension);
            }
        }
        ((MFileManager) UrlManager.getController()).save(map, chosenFile);
        final NodeModel newNode = mMapController.addNewNode(parent, nodePosition, existingNode.isLeft());
        ((MTextController) TextController.getController()).setNodeText(newNode, existingNode.getText());
        modeController.undoableCopyExtensions(LogicalStyleKeys.NODE_STYLE, existingNode, newNode);
        map.getFile();
        ((MLinkController) LinkController.getController()).setLink(newNode, newUri,
                LinkController.LINK_ABSOLUTE);
        map.destroy();
    }
}

From source file:org.gofleet.module.routing.RoutingMap.java

private void newPlan(LatLon from) {
    JDialog d = new JDialog(basicWindow.getFrame(), "Generating New Plan");
    try {//from   www.  j  a  v  a 2 s .  c o  m
        JFileChooser fc = new JFileChooser();
        fc.addChoosableFileFilter(new RoutingFilter());
        fc.setAcceptAllFileFilterUsed(true);
        int returnVal = fc.showOpenDialog(basicWindow.getFrame());
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            log.debug("Opening: " + file.getName());

            JProgressBar progressBar = new JProgressBar(0, getNumberLines(file) * 2);
            progressBar.setValue(0);
            progressBar.setPreferredSize(new Dimension(150, 50));
            progressBar.setStringPainted(true);

            d.add(progressBar);
            d.pack();
            d.setVisible(true);

            TSPPlan[] param = processFile(file, progressBar);

            Map<String, String> values = getValues(from);

            double[] origin = new double[2];
            origin[0] = new Double(values.get("origin_x"));
            origin[1] = new Double(values.get("origin_y"));

            TSPPlan[] res = calculateRouteOnWS(new Integer(values.get("maxDistance")),
                    new Integer(values.get("maxTime")), origin, new Integer(values.get("startTime")), param,
                    new Integer(values.get("timeSpentOnStop")));

            progressBar.setValue(progressBar.getMaximum() - res.length);

            processTSPPlan(res, progressBar);

        } else {
            log.trace("Open command cancelled by user.");
        }
    } catch (Throwable t) {
        log.error("Error computing new plan", t);
        JOptionPane.showMessageDialog(basicWindow.getFrame(),
                "<html><p>" + i18n.getString("Main.Error") + ":</p><p>" + t.toString() + "</p><html>",
                i18n.getString("Main.Error"), JOptionPane.ERROR_MESSAGE);
    } finally {
        d.setVisible(false);
        d.dispose();
    }

}

From source file:org.iobserve.mobile.instrument.start.InstrumenterTest.java

/**
 * Executes the instrumentation.//from   w ww . ja v  a 2 s .  c  o m
 * 
 * @param argv
 *            not needed
 * @throws KeyStoreException
 *             caused by the instrumentation
 * @throws NoSuchAlgorithmException
 *             caused by the instrumentation
 * @throws CertificateException
 *             caused by the instrumentation
 * @throws IOException
 *             caused by the instrumentation
 * @throws ZipException
 *             caused by the instrumentation
 * @throws URISyntaxException
 *             caused by the instrumentation
 */
public static void main(final String[] argv) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, ZipException, URISyntaxException {
    final File toInstrument;
    if (SELECTAPK) {
        final JFileChooser fc = new JFileChooser();
        fc.addChoosableFileFilter(new FileFilter() {
            @Override
            public String getDescription() {
                return null;
            }

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

                if (FilenameUtils.getExtension(f.getAbsolutePath()).equals("apk")) {
                    return true;
                }
                return false;
            }
        });
        fc.setAcceptAllFileFilterUsed(false);
        final int returnVal = fc.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            toInstrument = fc.getSelectedFile();
        } else {
            return;
        }
    } else {
        toInstrument = new File("app-debug.apk");
    }

    if (toInstrument.exists()) {
        final APKInstrumenter instr = new APKInstrumenter(true, new File("lib/release.keystore"),
                "androiddebugkey", "android");
        instr.instrumentAPK(toInstrument, new File("instr-output.apk"));
    } else {
        System.err.println("APK doesn't exist.");
    }
}

From source file:org.lnicholls.galleon.apps.iTunes.iTunesOptionsPanel.java

public void actionPerformed(ActionEvent e) {

    if ("pick".equals(e.getActionCommand())) {

        final JFileChooser fc = new JFileChooser();

        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

        fc.addChoosableFileFilter(new FileFilter() {

            public boolean accept(File f) {

                if (f.isDirectory()) {

                    return true;

                } else if (f.isFile() && f.getName().toLowerCase().endsWith("xml")) {

                    return true;

                }/*www.  j a  v  a2  s  .  c  om*/

                return false;

            }

            //The description of this filter

            public String getDescription() {

                return "Playlist Library";

            }

        });

        int returnVal = fc.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {

            File file = fc.getSelectedFile();

            mPlaylistPathField.setText(file.getAbsolutePath());

        }

    }

}

From source file:org.mbari.aved.ui.utils.VideoUtils.java

/**
 * Browse for video clip, or still image archive starting in last imported directory
 *//*from  w w  w.j  ava2s  .  c o  m*/
public static File browseForImageSource(File setCurrentDirectory) throws Exception {
    File f = null;

    // Add a custom file filter and disable the default
    JFileChooser chooser = new JFileChooser();

    chooser.addChoosableFileFilter(new ImageFileFilter());
    chooser.setAcceptAllFileFilterUsed(false);
    chooser.setDialogTitle("Choose Still Image/Video Source File");
    chooser.setCurrentDirectory(setCurrentDirectory);

    if (chooser.showOpenDialog(Application.getView()) == JFileChooser.APPROVE_OPTION) {
        f = chooser.getSelectedFile();
        UserPreferences.getModel().setImportVideoDir(f.getParent());
    } else {

        // TODO: print dialog message box with something meaningful here
        System.out.println("No Selection ");

        return null;
    }

    return f;
}