Example usage for javax.swing JFileChooser setCurrentDirectory

List of usage examples for javax.swing JFileChooser setCurrentDirectory

Introduction

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

Prototype

@BeanProperty(preferred = true, description = "The directory that the JFileChooser is showing files of.")
public void setCurrentDirectory(File dir) 

Source Link

Document

Sets the current directory.

Usage

From source file:AltiConsole.AltiConsoleMainScreen.java

/**
 * Handles all the actions.//w w w . j a  v  a 2  s.  c  om
 * 
 * @param e
 *            the action event.
 */
public void actionPerformed(final ActionEvent e) {
    final Translator trans = Application.getTranslator();

    if (e.getActionCommand().equals("EXIT")) {
        System.out.println("exit and disconnecting\n");
        if (JOptionPane.showConfirmDialog(this, trans.get("AltiConsoleMainScreen.ClosingWindow"),
                trans.get("AltiConsoleMainScreen.ReallyClosing"), JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
            DisconnectFromAlti();
            System.exit(0);
        }
    } else if (e.getActionCommand().equals("ABOUT")) {
        AboutDialog.showPreferences(AltiConsoleMainScreen.this);
    }
    // ERASE_FLIGHT
    else if (e.getActionCommand().equals("ERASE_FLIGHT")) {

        if (JOptionPane.showConfirmDialog(this, trans.get("AltiConsoleMainScreen.eraseAllflightData"),
                trans.get("AltiConsoleMainScreen.eraseAllflightDataTitle"), JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
            System.out.println("erasing flight\n");
            ErasingFlight();
        }

    } else if (e.getActionCommand().equals("RETRIEVE_FLIGHT")) {

        System.out.println("retrieving flight\n");
        RetrievingFlight();

    } else
    // SAVE_FLIGHT
    if (e.getActionCommand().equals("SAVE_FLIGHT")) {
        System.out.println("Saving current flight\n");
        SavingFlight();
    } else
    // RETRIEVE_ALTI_CFG
    if (e.getActionCommand().equals("RETRIEVE_ALTI_CFG")) {
        System.out.println("retrieving alti config\n");
        AltiConfigData pAlticonfig = retrieveAltiConfig();
        if (pAlticonfig != null)
            AltiConfigDlg.showPreferences(AltiConsoleMainScreen.this, pAlticonfig, Serial);

    }
    // LICENSE
    else if (e.getActionCommand().equals("LICENSE")) {

        LicenseDialog.showPreferences(AltiConsoleMainScreen.this);
    }
    // comPorts
    else if (e.getActionCommand().equals("comPorts")) {
        DisconnectFromAlti();
        String currentPort;
        //e.
        currentPort = (String) comPorts.getSelectedItem();
        if (Serial != null)
            Serial.searchForPorts();

        System.out.println("We have a new selected value for comport\n");
        comPorts.setSelectedItem(currentPort);
    }
    // UPLOAD_FIRMWARE
    else if (e.getActionCommand().equals("UPLOAD_FIRMWARE")) {
        System.out.println("upload firmware\n");
        //make sure to disconnect first
        DisconnectFromAlti();
        JFileChooser fc = new JFileChooser();
        String hexfile = null;
        File startFile = new File(System.getProperty("user.dir"));
        //FileNameExtensionFilter filter;

        fc.setDialogTitle("Select firmware");
        //fc.set
        fc.setCurrentDirectory(startFile);
        //fc.addChoosableFileFilter(new FileNameExtensionFilter("*.HEX", "hex"));
        fc.setFileFilter(new FileNameExtensionFilter("*.hex", "hex"));
        //fc.fil
        int action = fc.showOpenDialog(SwingUtilities.windowForComponent(this));
        if (action == JFileChooser.APPROVE_OPTION) {
            hexfile = fc.getSelectedFile().getAbsolutePath();
        }
        if (hexfile != null) {

            String exefile = UserPref.getAvrdudePath();

            String conffile = UserPref.getAvrdudeConfigPath();

            String opts = " -v -v -v -v -patmega328p -carduino -P\\\\.\\"
                    + (String) this.comPorts.getSelectedItem() + " -b115200 -D -V ";

            String cmd = exefile + " -C" + conffile + opts + " -Uflash:w:" + hexfile + ":i";
            System.out.println(cmd);

            try {
                Process p = Runtime.getRuntime().exec(cmd);
                AfficheurFlux fluxSortie = new AfficheurFlux(p.getInputStream(), this);
                AfficheurFlux fluxErreur = new AfficheurFlux(p.getErrorStream(), this);

                new Thread(fluxSortie).start();
                new Thread(fluxErreur).start();

                p.waitFor();
            } catch (IOException e1) {
                e1.printStackTrace();
            } catch (InterruptedException e2) {
                e2.printStackTrace();
            }
        }
    }
    // ON_LINE_HELP
    else if (e.getActionCommand().equals("ON_LINE_HELP")) {
        Desktop d = Desktop.getDesktop();
        System.out.println("Online help \n");
        try {
            d.browse(new URI(trans.get("help.url")));
        } catch (URISyntaxException e1) {

            System.out.println("Illegal URL:  " + trans.get("help.url") + " " + e1.getMessage());
        } catch (IOException e1) {
            System.out.println("Unable to launch browser: " + e1.getMessage());
        }

    }
}

From source file:edu.harvard.mcz.imagecapture.loader.JobVerbatimFieldLoad.java

@Override
public void start() {
    startDateTime = new Date();
    Singleton.getSingletonInstance().getJobList().addJob((RunnableJob) this);
    runStatus = RunStatus.STATUS_RUNNING;

    String selectedFilename = "";

    if (file == null) {
        final JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        if (Singleton.getSingletonInstance().getProperties().getProperties()
                .getProperty(ImageCaptureProperties.KEY_LASTLOADPATH) != null) {
            fileChooser.setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties()
                    .getProperties().getProperty(ImageCaptureProperties.KEY_LASTLOADPATH)));
        }//from w w w  .j a va 2 s  .  c om

        int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame());
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            file = fileChooser.getSelectedFile();
        }
    }

    if (file != null) {
        log.debug("Selected file to load: " + file.getName() + ".");

        if (file.exists() && file.isFile() && file.canRead()) {
            // Save location
            Singleton.getSingletonInstance().getProperties().getProperties()
                    .setProperty(ImageCaptureProperties.KEY_LASTLOADPATH, file.getPath());
            selectedFilename = file.getName();

            String[] headers = new String[] {};

            CSVFormat csvFormat = CSVFormat.DEFAULT.withHeader(headers);
            int rows = 0;
            try {
                rows = readRows(file, csvFormat);
            } catch (FileNotFoundException e) {
                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                        "Unable to load data, file not found: " + e.getMessage(), "Error: File Not Found",
                        JOptionPane.OK_OPTION);
                errors.append("File not found ").append(e.getMessage()).append("\n");
                log.error(e.getMessage(), e);
            } catch (IOException e) {
                errors.append("Error loading csv format, trying tab delimited: ").append(e.getMessage())
                        .append("\n");
                log.debug(e.getMessage());
                try {
                    // try reading as tab delimited format, if successful, use that format.
                    CSVFormat tabFormat = CSVFormat.newFormat('\t').withIgnoreSurroundingSpaces(true)
                            .withHeader(headers).withQuote('"');
                    rows = readRows(file, tabFormat);
                    csvFormat = tabFormat;
                } catch (IOException e1) {
                    errors.append("Error Loading data: ").append(e1.getMessage()).append("\n");
                    log.error(e.getMessage(), e1);
                }
            }

            try {
                Reader reader = new FileReader(file);

                CSVParser csvParser = new CSVParser(reader, csvFormat);

                Map<String, Integer> csvHeader = csvParser.getHeaderMap();
                headers = new String[csvHeader.size()];
                int i = 0;
                for (String header : csvHeader.keySet()) {
                    headers[i++] = header;
                    log.debug(header);
                }

                boolean okToRun = true;
                //TODO: Work picking/checking responsibility into a FieldLoaderWizard
                List<String> headerList = Arrays.asList(headers);
                if (!headerList.contains("barcode")) {
                    log.error("Input file " + file.getName()
                            + " header does not contain required field 'barcode'.");
                    // no barcode field, we can't match the input to specimen records.
                    errors.append("Field \"barcode\" not found in csv file headers.  Unable to load data.")
                            .append("\n");
                    okToRun = false;
                }

                if (okToRun) {

                    Iterator<CSVRecord> iterator = csvParser.iterator();

                    FieldLoader fl = new FieldLoader();

                    if (headerList.size() == 3 && headerList.contains("verbatimUnclassifiedText")
                            && headerList.contains("questions") && headerList.contains("barcode")) {
                        log.debug("Input file matches case 1: Unclassified text only.");
                        // Allowed case 1a: unclassified text only

                        int confirm = JOptionPane.showConfirmDialog(
                                Singleton.getSingletonInstance().getMainFrame(),
                                "Confirm load from file " + selectedFilename + " (" + rows
                                        + " rows) with just barcode and verbatimUnclassifiedText",
                                "Verbatim unclassified Field found for load", JOptionPane.OK_CANCEL_OPTION);
                        if (confirm == JOptionPane.OK_OPTION) {
                            String barcode = "";
                            int lineNumber = 0;
                            while (iterator.hasNext()) {
                                lineNumber++;
                                counter.incrementSpecimens();
                                CSVRecord record = iterator.next();
                                try {
                                    String verbatimUnclassifiedText = record.get("verbatimUnclassifiedText");
                                    barcode = record.get("barcode");
                                    String questions = record.get("questions");

                                    fl.load(barcode, verbatimUnclassifiedText, questions, true);
                                    counter.incrementSpecimensUpdated();
                                } catch (IllegalArgumentException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                } catch (LoadException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                }
                                percentComplete = (int) ((lineNumber * 100f) / rows);
                                this.setPercentComplete(percentComplete);
                            }
                        } else {
                            errors.append("Load canceled by user.").append("\n");
                        }
                    } else if (headerList.size() == 4 && headerList.contains("verbatimUnclassifiedText")
                            && headerList.contains("questions") && headerList.contains("barcode")
                            && headerList.contains("verbatimClusterIdentifier")) {
                        log.debug(
                                "Input file matches case 1: Unclassified text only (with cluster identifier).");
                        // Allowed case 1b: unclassified text only (including cluster identifier)

                        int confirm = JOptionPane.showConfirmDialog(
                                Singleton.getSingletonInstance().getMainFrame(),
                                "Confirm load from file " + selectedFilename + " (" + rows
                                        + " rows) with just barcode and verbatimUnclassifiedText",
                                "Verbatim unclassified Field found for load", JOptionPane.OK_CANCEL_OPTION);
                        if (confirm == JOptionPane.OK_OPTION) {
                            String barcode = "";
                            int lineNumber = 0;
                            while (iterator.hasNext()) {
                                lineNumber++;
                                counter.incrementSpecimens();
                                CSVRecord record = iterator.next();
                                try {
                                    String verbatimUnclassifiedText = record.get("verbatimUnclassifiedText");
                                    String verbatimClusterIdentifier = record.get("verbatimClusterIdentifier");
                                    barcode = record.get("barcode");
                                    String questions = record.get("questions");

                                    fl.load(barcode, verbatimUnclassifiedText, verbatimClusterIdentifier,
                                            questions, true);
                                    counter.incrementSpecimensUpdated();
                                } catch (IllegalArgumentException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                } catch (LoadException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                }
                                percentComplete = (int) ((lineNumber * 100f) / rows);
                                this.setPercentComplete(percentComplete);
                            }
                        } else {
                            errors.append("Load canceled by user.").append("\n");
                        }

                    } else if (headerList.size() == 8 && headerList.contains("verbatimUnclassifiedText")
                            && headerList.contains("questions") && headerList.contains("barcode")
                            && headerList.contains("verbatimLocality") && headerList.contains("verbatimDate")
                            && headerList.contains("verbatimNumbers")
                            && headerList.contains("verbatimCollector")
                            && headerList.contains("verbatimCollection")) {
                        // Allowed case two, transcription into verbatim fields, must be exact list of all
                        // verbatim fields, not including cluster identifier or other metadata.
                        log.debug("Input file matches case 2: Full list of verbatim fields.");

                        int confirm = JOptionPane.showConfirmDialog(
                                Singleton.getSingletonInstance().getMainFrame(),
                                "Confirm load from file " + selectedFilename + " (" + rows
                                        + " rows) with just barcode and verbatim fields.",
                                "Verbatim Fields found for load", JOptionPane.OK_CANCEL_OPTION);
                        if (confirm == JOptionPane.OK_OPTION) {

                            String barcode = "";
                            int lineNumber = 0;
                            while (iterator.hasNext()) {
                                lineNumber++;
                                counter.incrementSpecimens();
                                CSVRecord record = iterator.next();
                                try {
                                    String verbatimLocality = record.get("verbatimLocality");
                                    String verbatimDate = record.get("verbatimDate");
                                    String verbatimCollector = record.get("verbatimCollector");
                                    String verbatimCollection = record.get("verbatimCollection");
                                    String verbatimNumbers = record.get("verbatimNumbers");
                                    String verbatimUnclasifiedText = record.get("verbatimUnclassifiedText");
                                    barcode = record.get("barcode");
                                    String questions = record.get("questions");

                                    fl.load(barcode, verbatimLocality, verbatimDate, verbatimCollector,
                                            verbatimCollection, verbatimNumbers, verbatimUnclasifiedText,
                                            questions);
                                    counter.incrementSpecimensUpdated();
                                } catch (IllegalArgumentException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                } catch (LoadException e) {
                                    RunnableJobError error = new RunnableJobError(file.getName(), barcode,
                                            Integer.toString(lineNumber), e.getClass().getSimpleName(), e,
                                            RunnableJobError.TYPE_LOAD_FAILED);
                                    counter.appendError(error);
                                    log.error(e.getMessage(), e);
                                }
                                percentComplete = (int) ((lineNumber * 100f) / rows);
                                this.setPercentComplete(percentComplete);
                            }
                        } else {
                            errors.append("Load canceled by user.").append("\n");
                        }

                    } else {
                        // allowed case three, transcription into arbitrary sets verbatim or other fields
                        log.debug("Input file case 3: Arbitrary set of fields.");

                        // Check column headers before starting run.
                        boolean headersOK = false;

                        try {
                            HeaderCheckResult headerCheck = fl.checkHeaderList(headerList);
                            if (headerCheck.isResult()) {
                                int confirm = JOptionPane.showConfirmDialog(
                                        Singleton.getSingletonInstance().getMainFrame(),
                                        "Confirm load from file " + selectedFilename + " (" + rows
                                                + " rows) with headers: \n"
                                                + headerCheck.getMessage().replaceAll(":", ":\n"),
                                        "Fields found for load", JOptionPane.OK_CANCEL_OPTION);
                                if (confirm == JOptionPane.OK_OPTION) {
                                    headersOK = true;
                                } else {
                                    errors.append("Load canceled by user.").append("\n");
                                }
                            } else {
                                int confirm = JOptionPane.showConfirmDialog(
                                        Singleton.getSingletonInstance().getMainFrame(),
                                        "Problem found with headers in file, try to load anyway?\nHeaders: \n"
                                                + headerCheck.getMessage().replaceAll(":", ":\n"),
                                        "Problem in fields for load", JOptionPane.OK_CANCEL_OPTION);
                                if (confirm == JOptionPane.OK_OPTION) {
                                    headersOK = true;
                                } else {
                                    errors.append("Load canceled by user.").append("\n");
                                }
                            }
                        } catch (LoadException e) {
                            errors.append("Error loading data: \n").append(e.getMessage()).append("\n");
                            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                                    e.getMessage().replaceAll(":", ":\n"), "Error Loading Data: Problem Fields",
                                    JOptionPane.ERROR_MESSAGE);

                            log.error(e.getMessage(), e);
                        }

                        if (headersOK) {
                            int lineNumber = 0;
                            while (iterator.hasNext()) {
                                lineNumber++;
                                Map<String, String> data = new HashMap<String, String>();
                                CSVRecord record = iterator.next();
                                String barcode = record.get("barcode");
                                Iterator<String> hi = headerList.iterator();
                                boolean containsNonVerbatim = false;
                                while (hi.hasNext()) {
                                    String header = hi.next();
                                    // Skip any fields prefixed by the underscore character _
                                    if (!header.equals("barcode") && !header.startsWith("_")) {
                                        data.put(header, record.get(header));
                                        if (!header.equals("questions")
                                                && MetadataRetriever.isFieldExternallyUpdatable(Specimen.class,
                                                        header)
                                                && MetadataRetriever.isFieldVerbatim(Specimen.class, header)) {
                                            containsNonVerbatim = true;
                                        }
                                    }
                                }
                                if (data.size() > 0) {
                                    try {
                                        boolean updated = false;
                                        if (containsNonVerbatim) {
                                            updated = fl.loadFromMap(barcode, data,
                                                    WorkFlowStatus.STAGE_CLASSIFIED, true);
                                        } else {
                                            updated = fl.loadFromMap(barcode, data,
                                                    WorkFlowStatus.STAGE_VERBATIM, true);
                                        }
                                        counter.incrementSpecimens();
                                        if (updated) {
                                            counter.incrementSpecimensUpdated();
                                        }
                                    } catch (HibernateException e1) {
                                        // Catch (should just be development) problems with the underlying query 
                                        StringBuilder message = new StringBuilder();
                                        message.append("Query Error loading row (").append(lineNumber)
                                                .append(")[").append(barcode).append("]")
                                                .append(e1.getMessage());
                                        RunnableJobError err = new RunnableJobError(selectedFilename, barcode,
                                                Integer.toString(lineNumber), e1.getMessage(), e1,
                                                RunnableJobError.TYPE_LOAD_FAILED);
                                        counter.appendError(err);
                                        log.error(e1.getMessage(), e1);

                                    } catch (LoadException e) {
                                        StringBuilder message = new StringBuilder();
                                        message.append("Error loading row (").append(lineNumber).append(")[")
                                                .append(barcode).append("]").append(e.getMessage());

                                        RunnableJobError err = new RunnableJobError(selectedFilename, barcode,
                                                Integer.toString(lineNumber), e.getMessage(), e,
                                                RunnableJobError.TYPE_LOAD_FAILED);

                                        counter.appendError(err);
                                        // errors.append(message.append("\n").toString());
                                        log.error(e.getMessage(), e);
                                    }
                                }
                                percentComplete = (int) ((lineNumber * 100f) / rows);
                                this.setPercentComplete(percentComplete);
                            }
                        } else {
                            String message = "Can't load data, problem with headers.";
                            errors.append(message).append("\n");
                            log.error(message);
                        }
                    }
                }
                csvParser.close();
                reader.close();
            } catch (FileNotFoundException e) {
                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                        "Unable to load data, file not found: " + e.getMessage(), "Error: File Not Found",
                        JOptionPane.OK_OPTION);
                errors.append("File not found ").append(e.getMessage()).append("\n");
                log.error(e.getMessage(), e);
            } catch (IOException e) {
                errors.append("Error Loading data: ").append(e.getMessage()).append("\n");
                log.error(e.getMessage(), e);
            }
        }

    } else {
        //TODO: handle error condition
        log.error("File selection cancelled by user.");
    }

    report(selectedFilename);
    done();
}

From source file:de.juwimm.cms.content.panel.PanDocuments.java

private void upload(String prosa, Integer unit, Integer viewComponentId, Integer documentId) {
    this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    JFileChooser fc = new JFileChooser();
    int ff = fc.getChoosableFileFilters().length;
    FileFilter[] fft = fc.getChoosableFileFilters();
    for (int i = 0; i < ff; i++) {
        fc.removeChoosableFileFilter(fft[i]);
    }// w w  w.j  a va  2 s . c  o  m
    fc.addChoosableFileFilter(new DocumentFilter());
    fc.setAccessory(new ImagePreview(fc));
    fc.setDialogTitle(prosa);
    fc.setMultiSelectionEnabled(true);
    fc.setCurrentDirectory(Constants.LAST_LOCAL_UPLOAD_DIR);
    int returnVal = fc.showDialog(this, Messages.getString("panel.content.documents.addDocument"));

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File[] files = fc.getSelectedFiles();
        uploadFiles(files, unit, viewComponentId, documentId);
        Constants.LAST_LOCAL_UPLOAD_DIR = fc.getCurrentDirectory();
    }
    this.setCursor(Cursor.getDefaultCursor());
}

From source file:ctPrincipal.Principal.java

private File openImagem(String Dir, boolean lista) {
    JFileChooser fileChooser = new JFileChooser();
    BufferedImage buff = null;/*from   w  ww .  ja  va  2s.  c om*/
    String caminho = null;
    try {
        caminho = new File(".").getCanonicalPath() + Dir;
    } catch (IOException ex) {
        Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
    }
    fileChooser.setCurrentDirectory(new File(caminho));
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));
    fileChooser.setAcceptAllFileFilterUsed(true);
    fileChooser.setMultiSelectionEnabled(true);
    int result = fileChooser.showOpenDialog(getComponent(0));
    if (result == JFileChooser.APPROVE_OPTION) {
        if (lista) {
            File[] selectedFile = fileChooser.getSelectedFiles();
            arquivos = new String[selectedFile.length];
            for (int i = 0; i < selectedFile.length; i++) {
                selectedFile[i].setReadable(Boolean.TRUE);
                arquivos[i] = selectedFile[i].getAbsolutePath();
            }
            jLTotal.setText("Total de Imagens : " + arquivos.length);
        } else {
            File selectedFile = fileChooser.getSelectedFile();
            return selectedFile;
        }

    }
    return null;
}

From source file:org.gvsig.remotesensing.scatterplot.chart.ScatterPlotDiagram.java

/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format.//from   w  w  w.jav  a  2s . c o  m
 *
 * @throws IOException if there is an I/O error.
 */
public void doSaveAs() throws IOException {

    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setCurrentDirectory(this.defaultDirectoryForSaveAs);
    ExtensionFileFilter filter = new ExtensionFileFilter(localizationResources.getString("PNG_Image_Files"),
            ".png");
    fileChooser.addChoosableFileFilter(filter);

    int option = fileChooser.showSaveDialog(this);
    if (option == JFileChooser.APPROVE_OPTION) {
        String filename = fileChooser.getSelectedFile().getPath();
        if (isEnforceFileExtensions()) {
            if (!filename.endsWith(".png")) {
                filename = filename + ".png";
            }
        }
        ChartUtilities.saveChartAsPNG(new File(filename), this.chart, getWidth(), getHeight());
    }

}

From source file:com.jug.MotherMachine.java

/**
 * Shows a JFileChooser set up to accept the selection of folders.
 * If 'cancel' is pressed this method terminates the MotherMachine app.
 *
 * @param guiFrame//w ww  . j a v a 2 s .  c  o m
 *            parent frame
 * @param path
 *            path to the folder to open initially
 * @return an instance of {@link File} pointing at the selected folder.
 */
private File showFolderChooser(final JFrame guiFrame, final String path) {
    final JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File(path));
    chooser.setDialogTitle("Select folder containing image sequence...");
    chooser.setFileFilter(new FileFilter() {

        @Override
        public final boolean accept(final File file) {
            return file.isDirectory();
        }

        @Override
        public String getDescription() {
            return "We only take directories";
        }
    });
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);

    if (chooser.showOpenDialog(guiFrame) == JFileChooser.APPROVE_OPTION) {
        return chooser.getSelectedFile();
    } else {
        System.exit(0);
        return null;
    }
}

From source file:net.sf.jasperreports.swing.JRViewerToolbar.java

void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
    // Add your handling code here:

    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setLocale(this.getLocale());
    fileChooser.updateUI();//  w  w  w  .jav  a2s.com
    for (int i = 0; i < saveContributors.size(); i++) {
        fileChooser.addChoosableFileFilter(saveContributors.get(i));
    }

    if (saveContributors.contains(lastSaveContributor)) {
        fileChooser.setFileFilter(lastSaveContributor);
    } else if (saveContributors.size() > 0) {
        fileChooser.setFileFilter(saveContributors.get(0));
    }

    if (lastFolder != null) {
        fileChooser.setCurrentDirectory(lastFolder);
    }

    int retValue = fileChooser.showSaveDialog(this);
    if (retValue == JFileChooser.APPROVE_OPTION) {
        FileFilter fileFilter = fileChooser.getFileFilter();
        File file = fileChooser.getSelectedFile();

        lastFolder = file.getParentFile();

        JRSaveContributor contributor = null;

        if (fileFilter instanceof JRSaveContributor) {
            contributor = (JRSaveContributor) fileFilter;
        } else {
            int i = 0;
            while (contributor == null && i < saveContributors.size()) {
                contributor = saveContributors.get(i++);
                if (!contributor.accept(file)) {
                    contributor = null;
                }
            }

            if (contributor == null) {
                contributor = new JRPrintSaveContributor(viewerContext.getJasperReportsContext(), getLocale(),
                        viewerContext.getResourceBundle());
            }
        }

        lastSaveContributor = contributor;

        try {
            contributor.save(viewerContext.getJasperPrint(), file);
        } catch (JRException e) {
            if (log.isErrorEnabled()) {
                log.error("Save error.", e);
            }
            JOptionPane.showMessageDialog(this, viewerContext.getBundleString("error.saving"));
        }
    }
}

From source file:edu.harvard.mcz.imagecapture.PositionTemplateEditor.java

/**
 * This method initializes jMenuItem1   
 *    //from w ww .j a  v a  2  s  . com
 * @return javax.swing.JMenuItem   
 */
private JMenuItem getJMenuItemLoadImage() {
    if (jMenuItem1 == null) {
        jMenuItem1 = new JMenuItem();
        jMenuItem1.setText("Load Image");
        jMenuItem1.setMnemonic(KeyEvent.VK_L);
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                jLabelFeedback.setText("");
                final JFileChooser fileChooser = new JFileChooser();
                if (Singleton.getSingletonInstance().getProperties().getProperties()
                        .getProperty(ImageCaptureProperties.KEY_LASTPATH) != null) {
                    fileChooser.setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties()
                            .getProperties().getProperty(ImageCaptureProperties.KEY_LASTPATH)));
                }
                //FileNameExtensionFilter filter = new FileNameExtensionFilter("TIFF Images", "tif", "tiff");
                FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "tif", "tiff",
                        "jpg", "jpeg", "png");
                fileChooser.setFileFilter(filter);
                int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame());
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    jLabelFeedback.setText("Loading...");
                    try {
                        setImageFile(fileChooser.getSelectedFile());
                        jLabelFeedback.setText("");
                        drawLayers();
                    } catch (IOException e1) {
                        log.debug(e1);
                        jLabelFeedback.setText("Unable to load image.");
                    }
                }
                drawLayers();
            }
        });
    }
    return jMenuItem1;
}

From source file:org.gumtree.vis.awt.CompositePanel.java

/**
 * Opens a file chooser and gives the user an opportunity to save the chart
 * in PNG format./*from   ww w .j  a v a  2  s.c  o  m*/
 *
 * @throws IOException if there is an I/O error.
 */
@Override
public void doSaveAs() throws IOException {

    JFileChooser fileChooser = new JFileChooser();
    String currentDirectory = System.getProperty(StaticValues.SYSTEM_SAVE_PATH_LABEL);
    if (currentDirectory != null) {
        File savePath = new File(currentDirectory);
        if (savePath.exists() && savePath.isDirectory()) {
            fileChooser.setCurrentDirectory(savePath);
        }
    }
    ExtensionFileFilter pngFilter = new ExtensionFileFilter("PNG_Image_Files", ".png");
    ExtensionFileFilter jpgFilter = new ExtensionFileFilter("JPG_Image_Files", ".jpg");
    fileChooser.addChoosableFileFilter(pngFilter);
    fileChooser.addChoosableFileFilter(jpgFilter);

    int option = fileChooser.showSaveDialog(this);
    if (option == JFileChooser.APPROVE_OPTION) {
        String filename = fileChooser.getSelectedFile().getPath();
        String selectedDescription = fileChooser.getFileFilter().getDescription();
        String fileExtension = StaticValues.DEFAULT_IMAGE_FILE_EXTENSION;
        if (selectedDescription.toLowerCase().contains("png")) {
            fileExtension = "png";
            if (!filename.toLowerCase().endsWith(".png")) {
                filename = filename + ".png";
            }
        } else if (selectedDescription.toLowerCase().contains("jpg")) {
            fileExtension = "jpg";
            if (!filename.toLowerCase().endsWith(".jpg")) {
                filename = filename + ".jpg";
            }
        }
        File selectedFile = new File(filename);
        int confirm = JOptionPane.YES_OPTION;
        if (selectedFile.exists()) {
            confirm = JOptionPane.showConfirmDialog(this, selectedFile.getName() + " exists, overwrite?",
                    "Confirm Overwriting", JOptionPane.YES_NO_OPTION);
        }
        if (confirm == JOptionPane.YES_OPTION) {
            saveTo(filename, fileExtension);
            System.setProperty(StaticValues.SYSTEM_SAVE_PATH_LABEL, fileChooser.getSelectedFile().getParent());
        }
    }
}

From source file:ffx.ui.KeywordPanel.java

/**
 * <p>/*from   w  w w.  j a v a 2s. c  om*/
 * keySaveAs</p>
 */
public void keySaveAs() {
    if (!fileOpen) {
        return;
    }
    JFileChooser d = MainPanel.resetFileChooser();
    d.setDialogTitle("Save KEY File");
    d.setAcceptAllFileFilterUsed(false);
    if (currentKeyFile != null) {
        d.setCurrentDirectory(currentKeyFile.getParentFile());
        d.setSelectedFile(currentKeyFile);
    }
    d.setFileFilter(new KeyFileFilter());
    int result = d.showSaveDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
        currentKeyFile = d.getSelectedFile();
        keySave(currentKeyFile);
    }
}