Example usage for javax.swing JFileChooser getCurrentDirectory

List of usage examples for javax.swing JFileChooser getCurrentDirectory

Introduction

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

Prototype

public File getCurrentDirectory() 

Source Link

Document

Returns the current directory.

Usage

From source file:edu.ku.brc.specify.tasks.subpane.wb.ImageFrame.java

protected File[] askUserForImageFiles() {
    ImageFilter imageFilter = new ImageFilter();
    JFileChooser fileChooser = new JFileChooser(
            WorkbenchTask.getDefaultDirPath(WorkbenchTask.IMAGES_FILE_PATH));
    fileChooser.setFileFilter(imageFilter);
    fileChooser.setDialogTitle(getResourceString("WB_CHOOSE_IMAGES"));
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileChooser.setMultiSelectionEnabled(true);

    int userAction = fileChooser.showOpenDialog(this);
    AppPreferences localPrefs = AppPreferences.getLocalPrefs();

    // remember the directory the user was last in
    localPrefs.put(WorkbenchTask.IMAGES_FILE_PATH, fileChooser.getCurrentDirectory().getAbsolutePath());

    if (userAction == JFileChooser.APPROVE_OPTION) {
        return fileChooser.getSelectedFiles();
    }//ww  w .  ja  v a2 s.c o  m

    // if for any reason we got to this point...
    return null;
}

From source file:ElectionGUI.java

private void saveElectionBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveElectionBtnActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setApproveButtonText("Save");
    fileChooser.setCurrentDirectory(folder);
    int result = fileChooser.showOpenDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
        folder = fileChooser.getCurrentDirectory();
        File selectedFile = fileChooser.getSelectedFile();
        Store2dElection store = new Store2dElection(this, selectedFile);
        store.writeToFile();//from w  w  w.  j av a 2  s .co  m
        systemTxt.append("-Election saved successfully." + eol);
        saved = true;
    } else if (result == JFileChooser.CANCEL_OPTION) {
        systemTxt.append("-Saving cancelled" + eol);
    }
}

From source file:ElectionGUI.java

private void loadElectionBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadElectionBtnActionPerformed
    if (!generalPreferencesCheckBox.isSelected()) {
        //Confirmation of discarding an election2D that is not saved
        boolean discard = true;
        if (election2D != null && !saved) {
            int response = JOptionPane.showConfirmDialog(null,
                    "Current " + "election is not saved, are you sure you want to load " + "an election?" + eol
                            + "Press \"No\" to save current " + "election in a file.",
                    "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

            if (response == JOptionPane.NO_OPTION) {
                discard = false;//from   w ww.j  av a2 s  . co  m
            }
        }

        if (discard) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setCurrentDirectory(folder);
            int result = fileChooser.showOpenDialog(this);

            if (result == JFileChooser.APPROVE_OPTION) {
                folder = fileChooser.getCurrentDirectory();
                File selectedFile = fileChooser.getSelectedFile();
                Parse2dElection parser = new Parse2dElection();
                parser.parseFromFile(selectedFile);
                if (parser.getErr() == null) {
                    election2D = parser.getElection();
                    nTxtField.setText(String.valueOf(election2D.getNumberOfVoters()));
                    mTxtField.setText(String.valueOf(election2D.getNumberOfCandidates()));
                    kTxtField.setText(String.valueOf(election2D.getCommitteeSize()));
                    xLimit = parser.getxLimit();
                    xLimitTxtField.setText(String.valueOf(xLimit));
                    yLimit = parser.getyLimit();
                    yLimitTxtField.setText(String.valueOf(yLimit));
                    nClusters = parser.getnClusters();
                    nClusterTxtField.setText(String.valueOf(nClusters));
                    mClusters = parser.getmClusters();
                    mClusterTxtField.setText(String.valueOf(mClusters));

                    systemTxt.append("-Election loaded." + eol);
                    plotResultsBtn.setEnabled(true);
                    saveElectionBtn.setEnabled(true);
                    consistencyBtn.setEnabled(false);
                    saved = true;
                } else {
                    systemTxt.append(parser.getErr() + eol);
                }
            } else if (result == JFileChooser.CANCEL_OPTION) {
                systemTxt.append("-Loading cancelled." + eol);
            }
        }
    } else {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setCurrentDirectory(folder);
        int result = fileChooser.showOpenDialog(this);

        if (result == JFileChooser.APPROVE_OPTION) {
            folder = fileChooser.getCurrentDirectory();
            File selectedFile = fileChooser.getSelectedFile();
            ParseGeneralElection parser = new ParseGeneralElection();
            parser.parseFromFile(selectedFile);

            if (parser.getErr() == null) {
                ArrayList<Voter> voters = parser.getVoters();
                ArrayList<Candidate> candidates = parser.getCandidates();
                n = voters.size();
                m = candidates.size();
                try {
                    int x = Integer.parseInt(kTxtField.getText());
                    if (x < 1 || x > 100 || x > m) {
                        throw (new Exception());
                    }
                    k = x;
                } catch (Exception e) {
                    kTxtField.setBackground(Color.cyan);
                    kTxtField.setText("1");
                    k = 1;
                    systemTxt.append("-Committee size was invalid. It has " + "been set equal to 1." + eol);
                }

                electionGP = new Election(k, voters, candidates, false);
                plotResultsBtn.setEnabled(true);
                consistencyBtn.setEnabled(false);
                systemTxt
                        .append("-Election " + selectedFile.getName() + " has been loaded successfully." + eol);
            } else {
                systemTxt.append(parser.getErr() + eol);
            }
        } else if (result == JFileChooser.CANCEL_OPTION) {
            systemTxt.append("-Loading cancelled." + eol);
        }
    }
}

From source file:fll.scheduler.SchedulerUI.java

void saveScheduleDescription() {
    if (null == mScheduleDescriptionFile) {
        // prompt the user for a filename to save to

        final String startingDirectory = PREFS.get(DESCRIPTION_STARTING_DIRECTORY_PREF, null);

        final JFileChooser fileChooser = new JFileChooser();
        final FileFilter filter = new BasicFileFilter("FLL Schedule Description (properties)",
                new String[] { "properties" });
        fileChooser.setFileFilter(filter);
        if (null != startingDirectory) {
            fileChooser.setCurrentDirectory(new File(startingDirectory));
        }//from w ww . j ava  2 s. c o m

        final int returnVal = fileChooser.showSaveDialog(SchedulerUI.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            final File currentDirectory = fileChooser.getCurrentDirectory();
            PREFS.put(DESCRIPTION_STARTING_DIRECTORY_PREF, currentDirectory.getAbsolutePath());

            mScheduleDescriptionFile = fileChooser.getSelectedFile();
            mDescriptionFilename.setText(mScheduleDescriptionFile.getName());
        } else {
            // user canceled
            return;
        }
    }

    try (final Writer writer = new OutputStreamWriter(new FileOutputStream(mScheduleDescriptionFile),
            Utilities.DEFAULT_CHARSET)) {
        final SolverParams params = mScheduleDescriptionEditor.getParams();
        final List<String> errors = params.isValid();
        if (!errors.isEmpty()) {
            final String formattedErrors = errors.stream().collect(Collectors.joining("\n"));
            JOptionPane.showMessageDialog(SchedulerUI.this,
                    "There are errors that need to be corrected before the description can be saved: "
                            + formattedErrors,
                    "Error saving file", JOptionPane.ERROR_MESSAGE);
        } else {
            final Properties properties = new Properties();
            params.save(properties);
            properties.store(writer, null);
        }
    } catch (final IOException e) {
        final Formatter errorFormatter = new Formatter();
        errorFormatter.format("Error saving file: %s", e.getMessage());
        LOGGER.error(errorFormatter, e);
        JOptionPane.showMessageDialog(SchedulerUI.this, errorFormatter, "Error saving file",
                JOptionPane.ERROR_MESSAGE);
    }
}

From source file:ca.canucksoftware.ipkpackager.IpkPackagerView.java

private File loadFileChooser(boolean dir, FileFilter filter, String text) {
    File result = null;// w  ww .j  a  v  a 2  s .c o m
    JFileChooser fc = new JFileChooser(); //Create a file chooser
    disableNewFolderButton(fc);
    if (text != null) {
        fc.setSelectedFile(new File(text));
    }
    if (dir) {
        fc.setDialogTitle("");
        File lastDir = new File(
                Preferences.userRoot().get("lastDir", fc.getCurrentDirectory().getAbsolutePath()));
        fc.setCurrentDirectory(lastDir);
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (fc.showDialog(null, "Select") == JFileChooser.APPROVE_OPTION) {
            result = fc.getSelectedFile();
            jTextField1.setText(result.getAbsolutePath());
            Preferences.userRoot().put("lastDir", result.getParentFile().getAbsolutePath());
        }
    } else {
        File lastSaved = null;
        File lastSelected = null;
        if (filter != null) {
            fc.setDialogTitle("Save As...");
            lastSaved = new File(
                    Preferences.userRoot().get("lastSaved", fc.getCurrentDirectory().getAbsolutePath()));
            fc.setCurrentDirectory(lastSaved);
            fc.setFileFilter(filter);
        } else {
            fc.setDialogTitle("");
            lastSelected = new File(
                    Preferences.userRoot().get("lastSelected", fc.getCurrentDirectory().getAbsolutePath()));
            fc.setCurrentDirectory(lastSelected);
            fc.setAcceptAllFileFilterUsed(true);
        }
        if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
            result = fc.getSelectedFile();
            if (lastSaved != null) {
                Preferences.userRoot().put("lastSaved", result.getParentFile().getAbsolutePath());
            }
            if (lastSelected != null) {
                Preferences.userRoot().put("lastSelected", result.getParentFile().getAbsolutePath());
            }
        }
    }
    return result;
}

From source file:com.openbravo.pos.imports.JPanelCSVImport.java

private void jbtnDbDriverLibActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnDbDriverLibActionPerformed
    resetFields();/*ww w . j a  v a 2 s. c o  m*/

    // If CSV.last_file is null then use c:\ otherwise use saved dir
    JFileChooser chooser = new JFileChooser(last_folder == null ? "C:\\" : last_folder);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("csv files", "csv");
    chooser.setFileFilter(filter);
    chooser.showOpenDialog(null);
    File csvFile = chooser.getSelectedFile();
    // check if a file was selected        
    if (csvFile == null) {
        return;
    }

    File current_folder = chooser.getCurrentDirectory();
    // If we have a file lets save the directory for later use if it's different from the old
    if (last_folder == null || !last_folder.equals(current_folder.getAbsolutePath())) {
        AppConfig CSVConfig = new AppConfig(config_file);
        CSVConfig.load();
        CSVConfig.setProperty("CSV.last_folder", current_folder.getAbsolutePath());
        last_folder = current_folder.getAbsolutePath();

        try {
            CSVConfig.save();
        } catch (IOException ex) {
            Logger.getLogger(JPanelCSVImport.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    String csv = csvFile.getName();
    if (!(csv.trim().equals(""))) {
        csvFileName = csvFile.getAbsolutePath();
        jFileName.setText(csvFileName);
    }
}

From source file:eu.apenet.dpt.standalone.gui.DataPreparationToolGUI.java

private void wireUp() {
    fileItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            if (actionEvent.getSource() == fileItem) {
                currentLocation = new File(retrieveFromDb.retrieveOpenLocation());
                fileChooser.setCurrentDirectory(currentLocation);
                int returnedVal = fileChooser.showOpenDialog(getParent());

                if (returnedVal == JFileChooser.APPROVE_OPTION) {
                    currentLocation = fileChooser.getCurrentDirectory();
                    retrieveFromDb.saveOpenLocation(currentLocation.getAbsolutePath());

                    RootPaneContainer root = (RootPaneContainer) getRootPane().getTopLevelAncestor();
                    root.getGlassPane().setCursor(WAIT_CURSOR);
                    root.getGlassPane().setVisible(true);

                    File[] files = fileChooser.getSelectedFiles();
                    for (File file : files) {
                        if (file.isDirectory()) {
                            File[] fileArray = file.listFiles();
                            Arrays.sort(fileArray, new FileNameComparator());
                            for (File children : fileArray) {
                                if (isCorrect(children)) {
                                    xmlEadListModel.addFile(children);
                                }/*from  w  w  w .  ja  va  2  s .  c  o  m*/
                            }
                        } else {
                            if (isCorrect(file)) {
                                xmlEadListModel.addFile(file);
                            }
                        }
                    }

                    root.getGlassPane().setCursor(DEFAULT_CURSOR);
                    root.getGlassPane().setVisible(false);
                }
            }
        }
    });
    repositoryCodeItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            createOptionPaneForRepositoryCode();
        }
    });
    countryCodeItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            createOptionPaneForCountryCode();
        }
    });
    checksLoadingFilesItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            createOptionPaneForChecksLoadingFiles();
        }
    });
    createEag2012FromExistingEag2012.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser eagFileChooser = new JFileChooser();
            eagFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            eagFileChooser.setMultiSelectionEnabled(false);
            eagFileChooser.setCurrentDirectory(new File(retrieveFromDb.retrieveOpenLocation()));
            if (eagFileChooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
                currentLocation = eagFileChooser.getCurrentDirectory();
                retrieveFromDb.saveOpenLocation(currentLocation.getAbsolutePath());

                File eagFile = eagFileChooser.getSelectedFile();
                if (!Eag2012Frame.isUsed()) {
                    try {
                        if (ReadXml.isXmlFile(eagFile, "eag")) {
                            new Eag2012Frame(eagFile, getContentPane().getSize(),
                                    (ProfileListModel) getXmlEadList().getModel(), labels);
                        } else {
                            JOptionPane.showMessageDialog(rootPane,
                                    labels.getString("eag2012.errors.notAnEagFile"));
                        }
                    } catch (SAXException ex) {
                        if (ex instanceof SAXParseException) {
                            JOptionPane.showMessageDialog(rootPane,
                                    labels.getString("eag2012.errors.notAnEagFile"));
                        }
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (ParserConfigurationException ex) {
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (Exception ex) {
                        try {
                            JOptionPane.showMessageDialog(rootPane, labels.getString(ex.getMessage()));
                        } catch (Exception ex1) {
                            JOptionPane.showMessageDialog(rootPane, "Error...");
                        }
                    }
                }
            }
        }
    });
    createEag2012FromScratch.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (!Eag2012Frame.isUsed()) {
                new Eag2012Frame(getContentPane().getSize(), (ProfileListModel) getXmlEadList().getModel(),
                        labels, retrieveFromDb.retrieveCountryCode(), retrieveFromDb.retrieveRepositoryCode());
            }
        }
    });
    digitalObjectTypeItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (!DigitalObjectAndRightsOptionFrame.isInUse()) {
                JFrame DigitalObjectAndRightsOptionFrame = new DigitalObjectAndRightsOptionFrame(labels,
                        retrieveFromDb);

                DigitalObjectAndRightsOptionFrame.setPreferredSize(new Dimension(
                        getContentPane().getWidth() * 3 / 8, getContentPane().getHeight() * 3 / 4));
                DigitalObjectAndRightsOptionFrame.setLocation(getContentPane().getWidth() / 8,
                        getContentPane().getHeight() / 8);

                DigitalObjectAndRightsOptionFrame.pack();
                DigitalObjectAndRightsOptionFrame.setVisible(true);
            }
        }
    });
    defaultSaveFolderItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            JFileChooser defaultSaveFolderChooser = new JFileChooser();
            defaultSaveFolderChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            defaultSaveFolderChooser.setMultiSelectionEnabled(false);
            defaultSaveFolderChooser.setCurrentDirectory(new File(retrieveFromDb.retrieveDefaultSaveFolder()));
            if (defaultSaveFolderChooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
                File directory = defaultSaveFolderChooser.getSelectedFile();
                if (directory.canWrite() && DirectoryPermission.canWrite(directory)) {
                    retrieveFromDb.saveDefaultSaveFolder(directory + "/");
                } else {
                    createErrorOrWarningPanel(new Exception(labels.getString("error.directory.nowrites")),
                            false, labels.getString("error.directory.nowrites"), getContentPane());
                }
            }
        }
    });
    listDateConversionRulesItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            JDialog dateConversionRulesDialog = new DateConversionRulesDialog(labels, retrieveFromDb);

            dateConversionRulesDialog.setPreferredSize(
                    new Dimension(getContentPane().getWidth() * 3 / 8, getContentPane().getHeight() * 7 / 8));
            dateConversionRulesDialog.setLocation(getContentPane().getWidth() / 8,
                    getContentPane().getHeight() / 8);

            dateConversionRulesDialog.pack();
            dateConversionRulesDialog.setVisible(true);

        }
    });
    edmGeneralOptionsItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (!EdmGeneralOptionsFrame.isInUse()) {
                JFrame edmGeneralOptionsFrame = new EdmGeneralOptionsFrame(labels, retrieveFromDb);

                edmGeneralOptionsFrame.setPreferredSize(new Dimension(getContentPane().getWidth() * 3 / 8,
                        getContentPane().getHeight() * 3 / 8));
                edmGeneralOptionsFrame.setLocation(getContentPane().getWidth() / 8,
                        getContentPane().getHeight() / 8);

                edmGeneralOptionsFrame.pack();
                edmGeneralOptionsFrame.setVisible(true);
            }
        }
    });
    closeSelectedItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            xmlEadListModel.removeFiles(xmlEadList.getSelectedValues());
        }
    });
    saveSelectedItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String defaultOutputDirectory = retrieveFromDb.retrieveDefaultSaveFolder();
            boolean isMultipleFiles = xmlEadList.getSelectedIndices().length > 1;

            RootPaneContainer root = (RootPaneContainer) getRootPane().getTopLevelAncestor();
            root.getGlassPane().setCursor(WAIT_CURSOR);
            root.getGlassPane().setVisible(true);

            for (Object selectedValue : xmlEadList.getSelectedValues()) {
                File selectedFile = (File) selectedValue;
                String filename = selectedFile.getName();
                FileInstance fileInstance = fileInstances.get(filename);
                String filePrefix = fileInstance.getFileType().getFilePrefix();

                //todo: do we really need this?
                filename = filename.startsWith("temp_") ? filename.replace("temp_", "") : filename;

                filename = !filename.endsWith(".xml") ? filename + ".xml" : filename;

                if (!fileInstance.isValid()) {
                    filePrefix = "NOT_" + filePrefix;
                }

                if (fileInstance.getLastOperation().equals(FileInstance.Operation.EDIT_TREE)) {
                    TreeTableModel treeTableModel = tree.getTreeTableModel();
                    Document document = (Document) treeTableModel.getRoot();
                    try {
                        File file2 = new File(defaultOutputDirectory + filePrefix + "_" + filename);
                        File filetemp = new File(Utilities.TEMP_DIR + "temp_" + filename);
                        TransformerFactory tf = TransformerFactory.newInstance();
                        Transformer output = tf.newTransformer();
                        output.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
                        output.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

                        DOMSource domSource = new DOMSource(document.getFirstChild());
                        output.transform(domSource, new StreamResult(filetemp));
                        output.transform(domSource, new StreamResult(file2));

                        fileInstance.setLastOperation(FileInstance.Operation.SAVE);
                        fileInstance.setCurrentLocation(filetemp.getAbsolutePath());
                    } catch (Exception ex) {
                        createErrorOrWarningPanel(ex, true, labels.getString("errorSavingTreeXML"),
                                getContentPane());
                    }
                } else if (fileInstance.isConverted()) {
                    try {
                        File newFile = new File(defaultOutputDirectory + filePrefix + "_" + filename);
                        FileUtils.copyFile(new File(fileInstance.getCurrentLocation()), newFile);
                        fileInstance.setLastOperation(FileInstance.Operation.SAVE);
                        //                            fileInstance.setCurrentLocation(newFile.getAbsolutePath());
                    } catch (IOException ioe) {
                        LOG.error("Error when saving file", ioe);
                    }
                } else {
                    try {
                        File newFile = new File(defaultOutputDirectory + filePrefix + "_" + filename);
                        FileUtils.copyFile(selectedFile, newFile);
                        fileInstance.setLastOperation(FileInstance.Operation.SAVE);
                        //                            fileInstance.setCurrentLocation(newFile.getAbsolutePath());
                    } catch (IOException ioe) {
                        LOG.error("Error when saving file", ioe);
                    }
                }
            }

            root.getGlassPane().setCursor(DEFAULT_CURSOR);
            root.getGlassPane().setVisible(false);

            if (isMultipleFiles) {
                JOptionPane.showMessageDialog(getContentPane(),
                        MessageFormat.format(labels.getString("filesInOutput"), defaultOutputDirectory) + ".",
                        labels.getString("fileSaved"), JOptionPane.INFORMATION_MESSAGE, Utilities.icon);
            } else {
                JOptionPane.showMessageDialog(getContentPane(),
                        MessageFormat.format(labels.getString("fileInOutput"), defaultOutputDirectory) + ".",
                        labels.getString("fileSaved"), JOptionPane.INFORMATION_MESSAGE, Utilities.icon);
            }
            xmlEadList.updateUI();
        }
    });
    saveMessageReportItem.addActionListener(
            new MessageReportActionListener(retrieveFromDb, this, fileInstances, labels, this));
    sendFilesWebDAV.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    });
    quitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    });
    xsltItem.addActionListener(new XsltAdderActionListener(this, labels));
    xsdItem.addActionListener(new XsdAdderActionListener(this, labels, retrieveFromDb));
    if (Utilities.isDev) {
        databaseItem.addActionListener(new DatabaseCheckerActionListener(retrieveFromDb, getContentPane()));
    }
    xmlEadList.addMouseListener(new ListMouseAdapter(xmlEadList, xmlEadListModel, deleteFileItem, this));
    xmlEadList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
                if (xmlEadList.getSelectedValues() != null && xmlEadList.getSelectedValues().length != 0) {
                    if (xmlEadList.getSelectedValues().length > 1) {
                        //                            convertAndValidateBtn.setEnabled(true);
                        //                            validateSelectionBtn.setEnabled(true);
                        //                            if (isValidated(xmlEadList)) {
                        //                                convertEdmSelectionBtn.setEnabled(true);
                        //                            } else {
                        //                                convertEdmSelectionBtn.setEnabled(false);
                        //                            }
                        //                            disableAllBtnAndItems();
                        saveMessageReportItem.setEnabled(true);
                        changeInfoInGUI("");
                    } else {
                        //                            convertAndValidateBtn.setEnabled(false);
                        //                            validateSelectionBtn.setEnabled(false);
                        //                            convertEdmSelectionBtn.setEnabled(false);
                        changeInfoInGUI(((File) xmlEadList.getSelectedValue()).getName());
                        if (apePanel.getApeTabbedPane().getSelectedIndex() == APETabbedPane.TAB_EDITION) {
                            apePanel.getApeTabbedPane()
                                    .createEditionTree(((File) xmlEadList.getSelectedValue()));
                            if (tree != null) {
                                FileInstance fileInstance = fileInstances
                                        .get(((File) getXmlEadList().getSelectedValue()).getName());
                                tree.addMouseListener(new PopupMouseListener(tree, getDataPreparationToolGUI(),
                                        getContentPane(), fileInstance));
                            }
                        }
                        disableTabFlashing();
                    }
                    checkHoldingsGuideButton();
                } else {
                    //                        convertAndValidateBtn.setEnabled(false);
                    //                        validateSelectionBtn.setEnabled(false);
                    //                        convertEdmSelectionBtn.setEnabled(false);
                    createHGBtn.setEnabled(false);
                    analyzeControlaccessBtn.setEnabled(false);
                    changeInfoInGUI("");
                }
            }
        }

        private boolean isValidated(JList xmlEadList) {
            for (Object selectedValue : xmlEadList.getSelectedValues()) {
                File selectedFile = (File) selectedValue;
                String filename = selectedFile.getName();
                FileInstance fileInstance = fileInstances.get(filename);
                if (!fileInstance.isValid()) {
                    return false;
                }
            }
            return true;
        }
    });

    summaryWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_SUMMARY));
    validationWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_VALIDATION));
    conversionWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_CONVERSION));
    edmConversionWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_EDM));
    editionWindowItem.addActionListener(new TabItemActionListener(apePanel, APETabbedPane.TAB_EDITION));

    internetApexItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            BareBonesBrowserLaunch.openURL("http://www.apex-project.eu/");
        }
    });

    /**
     * Option Edit apeEAC-CPF file in the menu
     */

    this.editEacCpfFile.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser eacFileChooser = new JFileChooser();
            eacFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            eacFileChooser.setMultiSelectionEnabled(false);
            eacFileChooser.setCurrentDirectory(new File(retrieveFromDb.retrieveOpenLocation()));
            if (eacFileChooser.showOpenDialog(getParent()) == JFileChooser.APPROVE_OPTION) {
                currentLocation = eacFileChooser.getCurrentDirectory();
                retrieveFromDb.saveOpenLocation(currentLocation.getAbsolutePath());

                File eacFile = eacFileChooser.getSelectedFile();
                if (!EacCpfFrame.isUsed()) {
                    try {
                        if (ReadXml.isXmlFile(eacFile, "eac-cpf")) {
                            new EacCpfFrame(eacFile, true, getContentPane().getSize(),
                                    (ProfileListModel) getXmlEadList().getModel(), labels);
                        } else {
                            JOptionPane.showMessageDialog(rootPane,
                                    labels.getString("eaccpf.error.notAnEacCpfFile"));
                        }
                    } catch (SAXException ex) {
                        if (ex instanceof SAXParseException) {
                            JOptionPane.showMessageDialog(rootPane,
                                    labels.getString("eaccpf.error.notAnEacCpfFile"));
                        }
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (ParserConfigurationException ex) {
                        java.util.logging.Logger.getLogger(DataPreparationToolGUI.class.getName())
                                .log(java.util.logging.Level.SEVERE, null, ex);
                    } catch (Exception ex) {
                        try {
                            JOptionPane.showMessageDialog(rootPane, labels.getString(ex.getMessage()));
                        } catch (Exception ex1) {
                            JOptionPane.showMessageDialog(rootPane, "Error...");
                        }
                    }
                }
            }
        }
    });

    /**
     * Option Create apeEAC-CPF in the menu
     */
    this.createEacCpf.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (!EacCpfFrame.isUsed()) {
                EacCpfFrame eacCpfFrame = new EacCpfFrame(getContentPane().getSize(),
                        (ProfileListModel) getXmlEadList().getModel(), labels,
                        retrieveFromDb.retrieveCountryCode(), retrieveFromDb.retrieveRepositoryCode(), null,
                        null, null);
            }
        }
    });

}

From source file:com.att.aro.ui.model.diagnostic.GraphPanelHelper.java

public void SaveImageAs(JViewport pane, String graphPanelSaveDirectory) {

    JFileChooser fc = new JFileChooser(graphPanelSaveDirectory);

    // Set up file types
    String[] fileTypesJPG = new String[2];
    String fileDisplayTypeJPG = ResourceBundleHelper.getMessageString("fileChooser.contentDisplayType.jpeg");
    fileTypesJPG[0] = ResourceBundleHelper.getMessageString("fileChooser.contentType.jpeg");
    fileTypesJPG[1] = ResourceBundleHelper.getMessageString("fileChooser.contentType.jpg");
    FileFilter filterJPG = new ExtensionFileFilter(fileDisplayTypeJPG, fileTypesJPG);

    fc.addChoosableFileFilter(fc.getAcceptAllFileFilter());
    String[] fileTypesPng = new String[1];
    String fileDisplayTypePng = ResourceBundleHelper.getMessageString("fileChooser.contentDisplayType.png");
    fileTypesPng[0] = ResourceBundleHelper.getMessageString("fileChooser.contentType.png");
    FileFilter filterPng = new ExtensionFileFilter(fileDisplayTypePng, fileTypesPng);
    fc.addChoosableFileFilter(filterPng);
    fc.setFileFilter(filterJPG);/*from  ww  w  .j a va 2s  .  c  o m*/
    File plotImageFile = null;

    boolean bSavedOrCancelled = false;
    while (!bSavedOrCancelled) {
        if (fc.showSaveDialog(pane) == JFileChooser.APPROVE_OPTION) {
            String strFile = fc.getSelectedFile().toString();
            String strFileLowerCase = strFile.toLowerCase();
            String fileDesc = fc.getFileFilter().getDescription();
            String fileType = ResourceBundleHelper.getMessageString("fileChooser.contentType.jpg");
            if ((fileDesc.equalsIgnoreCase(
                    ResourceBundleHelper.getMessageString("fileChooser.contentDisplayType.png"))
                    || strFileLowerCase.endsWith(ResourceBundleHelper.getMessageString("fileType.filters.dot")
                            + fileTypesPng[0].toLowerCase()))) {
                fileType = fileTypesPng[0];
            }
            if (strFile.length() > 0) {
                // Save current directory
                graphPanelSaveDirectory = fc.getCurrentDirectory().getPath();

                if ((fileType != null) && (fileType.length() > 0)) {
                    String fileTypeLowerCaseWithDot = ResourceBundleHelper
                            .getMessageString("fileType.filters.dot") + fileType.toLowerCase();
                    if (!strFileLowerCase.endsWith(fileTypeLowerCaseWithDot)) {
                        strFile += ResourceBundleHelper.getMessageString("fileType.filters.dot") + fileType;
                    }
                }
                plotImageFile = new File(strFile);
                boolean bAttemptToWriteToFile = true;
                if (plotImageFile.exists()) {
                    if (MessageDialogFactory.showConfirmDialog(pane,
                            MessageFormat.format(
                                    ResourceBundleHelper.getMessageString("fileChooser.fileExists"),
                                    plotImageFile.getAbsolutePath()),
                            ResourceBundleHelper.getMessageString("fileChooser.confirm"),
                            JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
                        bAttemptToWriteToFile = false;
                    }
                }
                if (bAttemptToWriteToFile) {
                    try {
                        if (fileType != null && fileType.equalsIgnoreCase(fileTypesPng[0])) {
                            BufferedImage bufImage = ImageHelper.createImage(pane.getBounds().width,
                                    pane.getBounds().height);
                            Graphics2D g = bufImage.createGraphics();
                            pane.paint(g);
                            ImageIO.write(bufImage, "png", plotImageFile);
                        } else {
                            BufferedImage bufImage = ImageHelper.createImage(pane.getBounds().width,
                                    pane.getBounds().height);
                            Graphics2D g = bufImage.createGraphics();
                            pane.paint(g);
                            ImageIO.write(bufImage, "jpg", plotImageFile);
                        }
                        bSavedOrCancelled = true;
                    } catch (IOException e) {
                        MessageDialogFactory.showMessageDialog(pane, ResourceBundleHelper
                                .getMessageString("fileChooser.errorWritingToFile" + plotImageFile.toString()));
                    }
                }
            }
        } else {
            bSavedOrCancelled = true;
        }
    }
}

From source file:ded.ui.DiagramController.java

/** Prompt for a file name to load, then replace the current diagram with it. */
public void loadFromFile() {
    if (this.isDirty()) {
        int res = JOptionPane.showConfirmDialog(this, "There are unsaved changes.  Load new diagram anyway?",
                "Load Confirmation", JOptionPane.YES_NO_OPTION);
        if (res != JOptionPane.YES_OPTION) {
            return;
        }//from ww  w.ja  va  2  s  .co  m
    }

    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(this.currentFileChooserDirectory);
    chooser.addChoosableFileFilter(
            new FileNameExtensionFilter("Diagram and ER Editor Files (.ded, .png, .er)", "ded", "png", "er"));
    int res = chooser.showOpenDialog(this);
    if (res == JFileChooser.APPROVE_OPTION) {
        this.currentFileChooserDirectory = chooser.getCurrentDirectory();
        this.loadFromNamedFile(chooser.getSelectedFile().getAbsolutePath());
    }
}

From source file:ded.ui.DiagramController.java

/** Prompt user for file name and save to it. */
public void chooseAndSaveToFile() {
    // Prompt for a file name, confirming if the file already exists.
    String result = this.fileName;
    while (true) {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(this.currentFileChooserDirectory);
        chooser.addChoosableFileFilter(new FileNameExtensionFilter("Diagram Editor Files (.ded)", "ded"));
        int res = chooser.showSaveDialog(this);
        if (res != JFileChooser.APPROVE_OPTION) {
            return;
        }//from w  w  w. j a  va2s  .c  om
        this.currentFileChooserDirectory = chooser.getCurrentDirectory();
        result = chooser.getSelectedFile().getAbsolutePath();

        if (new File(result).exists()) {
            res = JOptionPane.showConfirmDialog(this,
                    "A file called \"" + result + "\" already exists.  Overwrite it?", "Confirm Overwrite",
                    JOptionPane.YES_NO_OPTION);
            if (res != JOptionPane.YES_OPTION) {
                continue; // Ask again.
            }
        }

        break;
    }

    // Save to the chosen file.
    this.saveToNamedFile(result);
}