Example usage for javax.swing JFileChooser setMultiSelectionEnabled

List of usage examples for javax.swing JFileChooser setMultiSelectionEnabled

Introduction

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

Prototype

@BeanProperty(description = "Sets multiple file selection mode.")
public void setMultiSelectionEnabled(boolean b) 

Source Link

Document

Sets the file chooser to allow multiple file selections.

Usage

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);
                                }//www  . ja  va  2 s  . c om
                            }
                        } 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:org.jets3t.apps.uploader.Uploader.java

/**
 * Handles GUI actions.//  w  w  w . j  ava2  s  . c om
 */
public void actionPerformed(ActionEvent actionEvent) {
    if ("Next".equals(actionEvent.getActionCommand())) {
        wizardStepForward();
    } else if ("Back".equals(actionEvent.getActionCommand())) {
        wizardStepBackward();
    } else if ("ChooseFile".equals(actionEvent.getActionCommand())) {
        JFileChooser fileChooser = new JFileChooser();

        if (validFileExtensions.size() > 0) {
            UploaderFileExtensionFilter filter = new UploaderFileExtensionFilter("Allowed files",
                    validFileExtensions);
            fileChooser.setFileFilter(filter);
        }

        fileChooser.setMultiSelectionEnabled(fileMaxCount > 1);
        fileChooser.setDialogTitle("Choose file" + (fileMaxCount > 1 ? "s" : "") + " to upload");
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setApproveButtonText("Choose file" + (fileMaxCount > 1 ? "s" : ""));

        int returnVal = fileChooser.showOpenDialog(ownerFrame);
        if (returnVal != JFileChooser.APPROVE_OPTION) {
            return;
        }

        List fileList = new ArrayList();
        if (fileChooser.getSelectedFiles().length > 0) {
            fileList.addAll(Arrays.asList(fileChooser.getSelectedFiles()));
        } else {
            fileList.add(fileChooser.getSelectedFile());
        }
        if (checkProposedUploadFiles(fileList)) {
            wizardStepForward();
        }
    } else if ("CancelUpload".equals(actionEvent.getActionCommand())) {
        if (uploadCancelEventTrigger != null) {
            uploadCancelEventTrigger.cancelTask(this);
            progressBar.setValue(0);
        } else {
            log.warn("Ignoring attempt to cancel file upload when cancel trigger is not available");
        }
    } else {
        log.warn("Unrecognised action command, ignoring: " + actionEvent.getActionCommand());
    }
}

From source file:org.fhaes.jsea.JSEAFrame.java

@Override
public void actionPerformed(ActionEvent event) {

    if (event.getActionCommand().equals("SegmentationMode")) {
        Boolean $success = this.validateDataFiles();

        if ($success == null) {
            log.debug("Files not set yet");
            return;
        } else if ($success == false) {
            log.debug("Invalid file ranges");
            return;
        }//w  ww . j  av  a 2 s.  c  o m

        if (segmentationPanel.chkSegmentation.isSelected() && chronologyYears.size() > 1) {
            segmentationPanel.table.setEarliestYear(Integer.parseInt(this.firstPossibleYear.toString()));
            segmentationPanel.table.setLatestYear(Integer.parseInt(this.lastPossibleYear.toString()));
        } else {
            // cannot perform segmentation if there are less than 2 years in the chronology
            segmentationPanel.chkSegmentation.setSelected(false);
        }
    } else if (event.getActionCommand().equals("AllYearsCheckbox")) {
        setYearRangeGUI();
    } else if (event.getActionCommand().equals("TimeSeriesFileBrowse")) {
        String lastVisitedFolder = App.prefs.getPref(PrefKey.PREF_LAST_READ_TIME_SERIES_FOLDER,
                App.prefs.getPref(PrefKey.PREF_LAST_READ_FOLDER, null));
        JFileChooser fc;

        if (lastVisitedFolder != null) {
            fc = new JFileChooser(lastVisitedFolder);
        } else {
            fc = new JFileChooser();
        }

        fc.setMultiSelectionEnabled(false);
        fc.setDialogTitle("Open file");

        fc.addChoosableFileFilter(new TXTFileFilter());
        fc.setAcceptAllFileFilterUsed(false);
        fc.setFileFilter(new CSVFileFilter());

        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            txtTimeSeriesFile.setText(fc.getSelectedFile().getAbsolutePath());
            txtwrapper.updatePref();

            App.prefs.setPref(PrefKey.PREF_LAST_READ_TIME_SERIES_FOLDER, fc.getSelectedFile().getPath());

            if (parseTimeSeriesFile()) {
                setYearRangeGUI();
            } else {
                txtTimeSeriesFile.setText("");
            }

            validateForm();
        }
    } else if (event.getActionCommand().equals("EventListFileBrowse")) {
        String lastVisitedFolder = App.prefs.getPref(PrefKey.PREF_LAST_READ_EVENT_LIST_FOLDER,
                App.prefs.getPref(PrefKey.PREF_LAST_READ_FOLDER, null));
        JFileChooser fc;

        if (lastVisitedFolder != null) {
            fc = new JFileChooser(lastVisitedFolder);
        } else {
            fc = new JFileChooser();
        }

        fc.setMultiSelectionEnabled(false);
        fc.setDialogTitle("Open file");

        int returnVal = fc.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            txtEventListFile.setText(fc.getSelectedFile().getAbsolutePath());
            App.prefs.setPref(PrefKey.PREF_LAST_READ_EVENT_LIST_FOLDER, fc.getSelectedFile().getPath());
            parseEventListFile();

            validateForm();
        }
    }
}

From source file:base.BasePlayer.AddGenome.java

@Override
public void mousePressed(MouseEvent e) {

    if (e.getSource() == tree) {

        if (selectedNode != null && selectedNode.toString().contains("Add new refe")) {
            try {
                FileDialog fs = new FileDialog(frame, "Select reference fasta-file", FileDialog.LOAD);
                fs.setDirectory(Main.downloadDir);
                fs.setVisible(true);/*from  w  ww .j av  a2s . c  o  m*/
                String filename = fs.getFile();
                fs.setFile("*.fasta;*.fa");
                fs.setFilenameFilter(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return name.toLowerCase().contains(".fasta") || name.toLowerCase().contains(".fa");
                    }
                });
                if (filename != null) {
                    File addfile = new File(fs.getDirectory() + "/" + filename);

                    if (addfile.exists()) {

                        genomeFile = addfile;
                        Main.downloadDir = genomeFile.getParent();
                        Main.writeToConfig("DownloadDir=" + genomeFile.getParent());
                        OutputRunner runner = new OutputRunner(genomeFile.getName().replace(".fasta", "")
                                .replace(".fa", "").replace(".gz", ""), genomeFile, null);
                        runner.createGenome = true;
                        runner.execute();
                    } else {
                        Main.showError("File does not exists.", "Error", frame);
                    }

                }
                if (1 == 1) {
                    return;
                }
                JFileChooser chooser = new JFileChooser(Main.downloadDir);
                chooser.setMultiSelectionEnabled(false);
                chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                chooser.setAcceptAllFileFilterUsed(false);
                MyFilterFasta fastaFilter = new MyFilterFasta();

                chooser.addChoosableFileFilter(fastaFilter);
                chooser.setDialogTitle("Select reference fasta-file");
                if (Main.screenSize != null) {
                    chooser.setPreferredSize(new Dimension((int) Main.screenSize.getWidth() / 3,
                            (int) Main.screenSize.getHeight() / 3));
                }

                int returnVal = chooser.showOpenDialog((Component) this.getParent());

                if (returnVal == JFileChooser.APPROVE_OPTION) {

                    genomeFile = chooser.getSelectedFile();
                    Main.downloadDir = genomeFile.getParent();
                    Main.writeToConfig("DownloadDir=" + genomeFile.getParent());
                    OutputRunner runner = new OutputRunner(
                            genomeFile.getName().replace(".fasta", "").replace(".gz", ""), genomeFile, null);
                    runner.createGenome = true;
                    runner.execute();

                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else if (selectedNode != null && selectedNode.isLeaf()
                && selectedNode.toString().contains("Add new anno")) {
            try {
                FileDialog fs = new FileDialog(frame, "Select annotation gff3/gtf-file", FileDialog.LOAD);
                fs.setDirectory(Main.downloadDir);
                fs.setVisible(true);
                String filename = fs.getFile();
                fs.setFile("*.gff3;*.gtf");
                fs.setFilenameFilter(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return name.toLowerCase().contains(".gff3") || name.toLowerCase().contains(".gtf");
                    }
                });

                if (filename != null) {
                    File addfile = new File(fs.getDirectory() + "/" + filename);

                    if (addfile.exists()) {
                        annotationFile = addfile;
                        Main.downloadDir = annotationFile.getParent();
                        Main.writeToConfig("DownloadDir=" + annotationFile.getParent());
                        OutputRunner runner = new OutputRunner(selectedNode.getParent().toString(), null,
                                annotationFile);
                        runner.createGenome = true;
                        runner.execute();
                    } else {
                        Main.showError("File does not exists.", "Error", frame);
                    }

                }
                if (1 == 1) {
                    return;
                }
                JFileChooser chooser = new JFileChooser(Main.downloadDir);
                chooser.setMultiSelectionEnabled(false);
                chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                chooser.setAcceptAllFileFilterUsed(false);
                MyFilterGFF gffFilter = new MyFilterGFF();

                chooser.addChoosableFileFilter(gffFilter);
                chooser.setDialogTitle("Select annotation gff3-file");
                if (Main.screenSize != null) {
                    chooser.setPreferredSize(new Dimension((int) Main.screenSize.getWidth() / 3,
                            (int) Main.screenSize.getHeight() / 3));
                }
                int returnVal = chooser.showOpenDialog((Component) this.getParent());

                if (returnVal == JFileChooser.APPROVE_OPTION) {

                    annotationFile = chooser.getSelectedFile();
                    Main.downloadDir = annotationFile.getParent();

                    Main.writeToConfig("DownloadDir=" + annotationFile.getParent());
                    OutputRunner runner = new OutputRunner(selectedNode.getParent().toString(), null,
                            annotationFile);
                    runner.createGenome = true;
                    runner.execute();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    if (e.getSource() == genometable) {

        if (new File(".").getFreeSpace()
                / 1048576 < sizeHash.get(genometable.getValueAt(genometable.getSelectedRow(), 0))[0]
                        / 1048576) {
            sizeError.setVisible(true);
            download.setEnabled(false);
            AddGenome.getLinks.setEnabled(false);
        } else {
            sizeError.setVisible(false);
            download.setEnabled(true);
            AddGenome.getLinks.setEnabled(true);
        }
        tree.clearSelection();
        remove.setEnabled(false);
        checkUpdates.setEnabled(false);
    }

}

From source file:base.BasePlayer.AddGenome.java

public void actionPerformed(ActionEvent event) {
    if (event.getSource() == download) {
        if (!downloading) {
            downloading = true;/*from   w ww . java 2s  .  co m*/
            downloadGenome(genometable.getValueAt(genometable.getSelectedRow(), 0).toString());
            downloading = false;
        }
    } else if (event.getSource() == getLinks) {
        URL[] urls = AddGenome.genomeHash
                .get(genometable.getValueAt(genometable.getSelectedRow(), 0).toString());
        JPopupMenu menu = new JPopupMenu();
        JTextArea area = new JTextArea();
        JScrollPane menuscroll = new JScrollPane();
        area.setFont(Main.menuFont);
        menu.add(menuscroll);
        menu.setPreferredSize(new Dimension(
                menu.getFontMetrics(Main.menuFont).stringWidth(urls[0].toString()) + Main.defaultFontSize * 10,
                (int) menu.getFontMetrics(Main.menuFont).getHeight() * 4));
        //area.setMaximumSize(new Dimension(300, 600));
        area.setLineWrap(true);
        area.setWrapStyleWord(true);
        for (int i = 0; i < urls.length; i++) {
            area.append(urls[i].toString() + "\n");
        }

        area.setCaretPosition(0);
        area.revalidate();
        menuscroll.getViewport().add(area);
        menu.pack();
        menu.show(this, 0, 0);

    } else if (event.getSource() == checkEnsembl) {
        if (ensemblfetch) {
            menu.show(AddGenome.treescroll, 0, 0);
        } else {
            EnsemblFetch fetcher = new EnsemblFetch();
            fetcher.execute();
        }
    } else if (event.getSource() == checkUpdates) {
        URL testfile = null;
        try {
            // kattoo onko paivityksia annotaatioon
            String ref = selectedNode.toString();
            if (AddGenome.genomeHash.get(ref) != null) {
                ArrayList<String> testfiles = new ArrayList<String>();
                if (Main.drawCanvas != null) {
                    for (int i = 0; i < Main.genomehash.get(ref).size(); i++) {
                        testfiles.add(Main.genomehash.get(ref).get(i).getName().replace(".bed.gz", ""));
                    }
                }
                testfile = AddGenome.genomeHash.get(ref)[1];
                String result = Main.checkFile(testfile, testfiles);

                if (result.length() == 0) {
                    Main.showError("You have newest annotation file.", "Note");
                } else {
                    int n = JOptionPane.showConfirmDialog(Main.drawCanvas,
                            "New annotation file found: " + result + "\nDownload it now?", "Note",
                            JOptionPane.YES_NO_OPTION);
                    if (n == JOptionPane.YES_OPTION) {
                        URL fileurl = new URL(testfile.getProtocol() + "://" + testfile.getHost()
                                + testfile.getPath().substring(0, testfile.getPath().lastIndexOf("/") + 1)
                                + result);
                        OutputRunner runner = new OutputRunner(fileurl, ref);
                        runner.downloadAnnotation = true;
                        runner.execute();
                    }
                }
            } else {
                Main.showError("This genome is not from Ensembl list, could not check for updates.", "Note",
                        AddGenome.genometable);
            }
        } catch (Exception e) {
            Main.showError("Cannot connect to " + testfile.getHost() + ".\nTry again later.", "Error");
            e.printStackTrace();
        }
    } else if (event.getSource() == remove) {
        if (!selectedNode.isLeaf()) {
            String removeref = selectedNode.toString();
            //   Boolean same = false;
            try {
                if (Main.drawCanvas != null) {
                    if (removeref.equals(Main.refDropdown.getSelectedItem().toString())) {
                        Main.referenceFile.close();
                        //      same = true;
                        if (ChromDraw.exonReader != null) {
                            ChromDraw.exonReader.close();
                        }
                    }
                }
                if (Main.genomehash.containsKey(removeref)) {
                    for (int i = Main.genomehash.get(removeref).size() - 1; i >= 0; i--) {
                        Main.genomehash.get(removeref).remove(i);
                    }
                    Main.genomehash.remove(removeref);

                }
                if (Main.drawCanvas != null) {
                    Main.refModel.removeElement(removeref);
                    Main.refDropdown.removeItem(removeref);
                    Main.refDropdown.revalidate();
                }

                for (int i = 0; i < Main.genome.getItemCount(); i++) {
                    if (Main.genome.getItem(i).getName() != null) {

                        if (Main.genome.getItem(i).getName().equals(removeref)) {
                            Main.genome.remove(Main.genome.getItem(i));
                            break;
                        }
                    }
                }

                FileUtils.deleteDirectory(new File(Main.genomeDir.getCanonicalPath() + "/" + removeref));
                checkGenomes();
                Main.setAnnotationDrop("");

                if (Main.genomehash.size() == 0) {
                    Main.refDropdown.setSelectedIndex(0);
                    Main.setChromDrop("-1");
                }
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    Main.showError("Could not delete genome folder.\nYou can do it manually by deleting folder "
                            + Main.genomeDir.getCanonicalPath() + "/" + removeref, "Note");
                } catch (IOException e1) {

                    e1.printStackTrace();
                }
            }
        } else {
            try {
                if (Main.drawCanvas != null) {
                    if (ChromDraw.exonReader != null) {
                        ChromDraw.exonReader.close();
                    }
                }

                Main.removeAnnotationFile(selectedNode.getParent().toString(), selectedNode.toString());

                FileUtils.deleteDirectory(new File(Main.genomeDir.getCanonicalPath() + "/"
                        + selectedNode.getParent().toString() + "/annotation/" + selectedNode.toString()));

                //   root.remove(selectedNode.getParent().getIndex(selectedNode));
                //   root.remove
                //   checkGenomes();

            } catch (Exception e) {
                e.printStackTrace();
                try {
                    Main.showError("Could not delete genome folder.\nYou can do it manually by deleting folder "
                            + Main.genomeDir.getCanonicalPath() + "/" + selectedNode.getParent().toString()
                            + "/annotation/" + selectedNode.toString(), "Note");
                } catch (IOException e1) {

                    e1.printStackTrace();
                }
            }
            treemodel.removeNodeFromParent(selectedNode);
        }

    } else if (event.getSource() == add) {

        if (genomeFile == null) {
            if (new File(genomeFileText.getText()).exists()) {
                genomeFile = new File(genomeFileText.getText());

            } else {
                genomeFileText.setText("Select reference genome fasta-file.");
                genomeFileText.setForeground(Color.red);
                return;
            }
        }

        /*if(genomeName.getText().contains("Give name") || genomeName.getText().length() == 0) {
           genomeName.setText("Give name of the genome");
           genomeName.setForeground(Color.red);
           genomeName.revalidate();
                   
        }
        else if(!annotation && new File(Main.userDir +"/genomes/"+genomeName.getText().trim().replace("\\s+", "_")).exists()) {
           genomeName.setText("This genome exists already.");
           genomeName.setForeground(Color.red);
           genomeName.revalidate();
        }
        else */

        if ((genomeFileText.getText().length() == 0
                || genomeFileText.getText().startsWith("Select reference"))) {
            genomeFileText.setText("Select reference genome fasta-file.");
            genomeFileText.setForeground(Color.red);
            genomeFileText.revalidate();
        }

        else {

            OutputRunner runner = new OutputRunner(
                    genomeFile.getName().replace(".fasta", "").replace(".gz", ""), genomeFile, annotationFile);
            runner.execute();
        }

    } else if (event.getSource() == openRef) {
        try {

            JFileChooser chooser = new JFileChooser(Main.downloadDir);
            chooser.setMultiSelectionEnabled(false);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            chooser.setAcceptAllFileFilterUsed(false);
            MyFilterFasta fastaFilter = new MyFilterFasta();

            chooser.addChoosableFileFilter(fastaFilter);
            chooser.setDialogTitle("Select reference fasta-file");
            if (Main.screenSize != null) {
                chooser.setPreferredSize(new Dimension((int) Main.screenSize.getWidth() / 3,
                        (int) Main.screenSize.getHeight() / 3));
            }

            int returnVal = chooser.showOpenDialog((Component) this.getParent());

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                genomeFile = chooser.getSelectedFile();
                Main.downloadDir = genomeFile.getParent();
                Main.writeToConfig("DownloadDir=" + genomeFile.getParent());
                genomeFileText.setText(genomeFile.getName());
                genomeFileText.revalidate();
                frame.pack();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    } else if (event.getSource() == openAnno) {
        try {

            JFileChooser chooser = new JFileChooser(Main.downloadDir);
            chooser.setMultiSelectionEnabled(false);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            chooser.setAcceptAllFileFilterUsed(false);
            MyFilterGFF gffFilter = new MyFilterGFF();

            chooser.addChoosableFileFilter(gffFilter);
            chooser.setDialogTitle("Select annotation gff3-file");
            if (Main.screenSize != null) {
                chooser.setPreferredSize(new Dimension((int) Main.screenSize.getWidth() / 3,
                        (int) Main.screenSize.getHeight() / 3));
            }
            int returnVal = chooser.showOpenDialog((Component) this.getParent());

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                if (genomeFile == null) {
                    genomeFile = Main.fastahash.get(Main.hoverGenome);
                }
                annotationFile = chooser.getSelectedFile();
                Main.downloadDir = annotationFile.getParent();
                Main.writeToConfig("DownloadDir=" + annotationFile.getParent());

                OutputRunner runner = new OutputRunner(
                        genomeFile.getName().replace(".fasta", "").replace(".gz", ""), genomeFile,
                        annotationFile);
                runner.execute();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.igormaznitsa.sciareto.ui.MainFrame.java

private void menuOpenProjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuOpenProjectActionPerformed
    final JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileView(new FileView() {
        private Icon KNOWLEDGE_FOLDER_ICO = null;

        @Override/*w  w w . j a v  a2  s .c  o  m*/
        public Icon getIcon(final File f) {
            if (f.isDirectory()) {
                final File knowledge = new File(f, ".projectKnowledge");
                if (knowledge.isDirectory()) {
                    if (KNOWLEDGE_FOLDER_ICO == null) {
                        final Icon icon = UIManager.getIcon("FileView.directoryIcon");
                        if (icon != null) {
                            KNOWLEDGE_FOLDER_ICO = new ImageIcon(
                                    UiUtils.makeBadgedRightBottom(UiUtils.iconToImage(fileChooser, icon),
                                            Icons.MMDBADGE.getIcon().getImage()));
                        }
                    }
                    return KNOWLEDGE_FOLDER_ICO;
                } else {
                    return super.getIcon(f);
                }
            } else if (f.isFile() && f.getName().toLowerCase(Locale.ENGLISH).endsWith(".mmd")) {
                return Icons.DOCUMENT.getIcon();
            } else {
                return super.getIcon(f);
            }
        }
    });
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    fileChooser.setMultiSelectionEnabled(false);
    fileChooser.setDialogTitle("Open project folder");

    if (fileChooser.showOpenDialog(Main.getApplicationFrame()) == JFileChooser.APPROVE_OPTION) {
        openProject(fileChooser.getSelectedFile(), false);
    }
}

From source file:com.lfv.lanzius.server.LanziusServer.java

public void menuChoiceLoadExercise() {
    if (isSwapping)
        return;/*from   w w  w.  jav  a 2 s  .  c om*/
    log.info("Menu: Load exercise");
    JFileChooser fc = new JFileChooser("data/exercises");
    fc.setDialogTitle("Load exercise...");
    fc.setMultiSelectionEnabled(false);
    fc.setFileFilter(new FileFilter() {
        public boolean accept(File f) {
            return !f.isHidden() && (f.isDirectory() || f.getName().endsWith(".xml"));
        }

        public String getDescription() {
            return "Exercise (*.xml)";
        }
    });

    int returnVal = JFileChooser.APPROVE_OPTION;
    if (Config.SERVER_AUTOLOAD_EXERCISE == null)
        returnVal = fc.showOpenDialog(frame);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        //File file;
        if (Config.SERVER_AUTOLOAD_EXERCISE == null)
            exerciseFile = fc.getSelectedFile();
        else
            exerciseFile = new File(Config.SERVER_AUTOLOAD_EXERCISE);
        log.info("Loading exercise " + exerciseFile);
        if (exerciseFile.exists()) {
            loadExercise(exerciseFile);
        } else
            JOptionPane.showMessageDialog(frame, "Unable to load exercise! File not found!", "Error!",
                    JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.lfv.lanzius.server.LanziusServer.java

private void menuChoiceLoadConfiguration() {
    if (isSwapping)
        return;//  ww  w  .  jav a 2  s.c  o m
    log.info("Menu: Load configuration");
    JFileChooser fc = new JFileChooser("data/configurations");
    fc.setDialogTitle("Load configuration...");
    fc.setMultiSelectionEnabled(false);
    fc.setFileFilter(new FileFilter() {
        public boolean accept(File f) {
            return !f.isHidden() && (f.isDirectory() || f.getName().endsWith(".xml"));
        }

        public String getDescription() {
            return "Configuration (*.xml)";
        }
    });

    int returnVal = JFileChooser.APPROVE_OPTION;
    if (Config.SERVER_AUTOLOAD_CONFIGURATION == null)
        returnVal = fc.showOpenDialog(frame);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file;
        if (Config.SERVER_AUTOLOAD_CONFIGURATION == null)
            file = fc.getSelectedFile();
        else
            file = new File(Config.SERVER_AUTOLOAD_CONFIGURATION);
        log.info("Loading configuration " + file);
        if (file.exists()) {
            if (buildConfigurationDocument(file)) {
                isConfigLoaded = true;
                updateView();
            } else
                JOptionPane.showMessageDialog(frame,
                        "Invalid configuration file! Make sure that all required tags are defined!", "Error!",
                        JOptionPane.ERROR_MESSAGE);
        } else
            JOptionPane.showMessageDialog(frame, "Unable to load configuration! File not found!", "Error!",
                    JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.jets3t.apps.cockpit.Cockpit.java

/**
 * Event handler for this application, handles all menu items.
 *///from   w  w  w  . ja  v  a 2  s . co m
public void actionPerformed(ActionEvent event) {
    // Service Menu Events
    if ("LoginEvent".equals(event.getActionCommand())) {
        loginEvent(null);
    } else if ("LogoutEvent".equals(event.getActionCommand())) {
        logoutEvent();
    } else if (event.getActionCommand() != null && event.getActionCommand().startsWith("LoginSwitch")) {
        String loginName = event.getActionCommand().substring("LoginSwitch:".length());
        ProviderCredentials credentials = loginAwsCredentialsMap.get(loginName);
        loginEvent(credentials);
    } else if ("QuitEvent".equals(event.getActionCommand())) {
        System.exit(0);
    }

    // Bucket Events.
    else if ("ViewBucketProperties".equals(event.getActionCommand())) {
        listBucketProperties();
    } else if ("RefreshBuckets".equals(event.getActionCommand())) {
        listAllBuckets();
    } else if ("CreateBucket".equals(event.getActionCommand())) {
        createBucketAction();
    } else if ("DeleteBucket".equals(event.getActionCommand())) {
        deleteSelectedBucket();
    } else if ("ManageDistributions".equals(event.getActionCommand())) {
        S3Bucket[] buckets = bucketTableModel.getBuckets();
        String[] bucketNames = new String[buckets.length];
        for (int i = 0; i < buckets.length; i++) {
            bucketNames[i] = buckets[i].getName();
        }
        ManageDistributionsDialog.showDialog(ownerFrame, cloudFrontService, bucketNames, this);
    } else if ("AddThirdPartyBucket".equals(event.getActionCommand())) {
        addThirdPartyBucket();
    } else if ("UpdateBucketACL".equals(event.getActionCommand())) {
        updateBucketAccessControlList();
    } else if ("UpdateBucketRequesterPaysStatus".equals(event.getActionCommand())) {
        updateBucketRequesterPaysSetting();
    }

    // Object Events
    else if ("ViewOrModifyObjectAttributes".equals(event.getActionCommand())) {
        displayObjectsAttributesDialog();
    } else if ("CopyObjects".equals(event.getActionCommand())) {
        copyObjects();
    } else if ("RefreshObjects".equals(event.getActionCommand())) {
        listObjects();
    } else if ("UpdateObjectACL".equals(event.getActionCommand())) {
        displayAclModificationDialog();
    } else if ("GeneratePublicGetURLs".equals(event.getActionCommand())) {
        generatePublicGetUrls();
    } else if ("GenerateTorrentURL".equals(event.getActionCommand())) {
        generateTorrentUrl();
    } else if ("DeleteObjects".equals(event.getActionCommand())) {
        deleteSelectedObjects();
    } else if ("DownloadObjects".equals(event.getActionCommand())) {
        downloadSelectedObjects();
    } else if ("UploadFiles".equals(event.getActionCommand())) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setMultiSelectionEnabled(true);
        fileChooser.setDialogTitle("Choose files to upload");
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        fileChooser.setApproveButtonText("Upload files");
        fileChooser.setCurrentDirectory(fileChoosersLastUploadDirectory);

        int returnVal = fileChooser.showOpenDialog(ownerFrame);
        if (returnVal != JFileChooser.APPROVE_OPTION) {
            return;
        }

        final File[] uploadFiles = fileChooser.getSelectedFiles();
        if (uploadFiles.length == 0) {
            return;
        }

        // Save the chosen directory location for next time.
        fileChoosersLastUploadDirectory = uploadFiles[0].getParentFile();

        uploadFiles(uploadFiles);
    } else if (event.getSource().equals(filterObjectsCheckBox)) {
        if (filterObjectsCheckBox.isSelected()) {
            filterObjectsPanel.setVisible(true);
        } else {
            filterObjectsPanel.setVisible(false);
            filterObjectsPrefix.setText("");
            if (filterObjectsDelimiter.getSelectedIndex() != 0) {
                filterObjectsDelimiter.setSelectedIndex(0);
            }
        }
    }

    // Tools events
    else if ("BucketLogging".equals(event.getActionCommand())) {
        S3Bucket[] buckets = bucketTableModel.getBuckets();
        BucketLoggingDialog.showDialog(ownerFrame, s3ServiceMulti.getS3Service(), buckets, this);
    }

    // Preference Events
    else if ("PreferencesDialog".equals(event.getActionCommand())) {
        PreferencesDialog.showDialog(cockpitPreferences, ownerFrame, this);

        // Save a user's preferences if requested, otherwise wipe any existing preferences file.
        File cockpitPreferencesPropertiesFile = new File(cockpitHomeDirectory,
                Constants.COCKPIT_PROPERTIES_FILENAME);
        if (cockpitPreferences.isRememberPreferences()) {
            try {
                Properties properties = cockpitPreferences.toProperties();
                if (!cockpitHomeDirectory.exists()) {
                    cockpitHomeDirectory.mkdir();
                }
                properties.list(new PrintStream(new FileOutputStream(cockpitPreferencesPropertiesFile)));
            } catch (IOException e) {
                String message = "Unable to save your preferences";
                log.error(message, e);
                ErrorDialog.showDialog(ownerFrame, this, message, e);
            }
        } else if (cockpitPreferencesPropertiesFile.exists()) {
            // User elected not to store preferences, delete the existing preferences file.
            cockpitPreferencesPropertiesFile.delete();
        }

        if (cockpitPreferences.isEncryptionPasswordSet()) {
            try {
                encryptionUtil = new EncryptionUtil(cockpitPreferences.getEncryptionPassword(),
                        cockpitPreferences.getEncryptionAlgorithm(), EncryptionUtil.DEFAULT_VERSION);
            } catch (Exception e) {
                String message = "Unable to start encryption utility";
                log.error(message, e);
                ErrorDialog.showDialog(ownerFrame, this, message, e);
            }
        } else {
            encryptionUtil = null;
        }
    }

    // Ooops...
    else {
        log.debug("Unrecognised ActionEvent command '" + event.getActionCommand() + "' in " + event);
    }
}

From source file:org.jets3t.apps.cockpit.Cockpit.java

/**
 * Downloads the objects currently selected in the objects table. The user is
 * prompted/*from  w w w .  j  a  v  a2 s  .  c  o  m*/
 * Prepares to perform a download of objects from S3 by prompting the user for a directory
 * to store the files in, then performing the download.
 *
 * @throws IOException
 */
private void downloadSelectedObjects() {
    // Prompt user to choose directory location for downloaded files (or cancel download altogether)
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Choose directory to save S3 files in");
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    fileChooser.setMultiSelectionEnabled(false);
    fileChooser.setSelectedFile(downloadDirectory);

    int returnVal = fileChooser.showDialog(ownerFrame, "Choose Directory");
    if (returnVal != JFileChooser.APPROVE_OPTION) {
        return;
    }

    downloadDirectory = fileChooser.getSelectedFile();

    boolean storeEmptyDirectories = Jets3tProperties.getInstance(Constants.JETS3T_PROPERTIES_FILENAME)
            .getBoolProperty("uploads.storeEmptyDirectories", true);
    final Map<String, String> objectKeyToFilepathMap = FileComparer.getInstance()
            .buildObjectKeyToFilepathMap(downloadDirectory.listFiles(), "", storeEmptyDirectories);

    // Build map of S3 Objects being downloaded.
    final Map s3DownloadObjectsMap = FileComparer.getInstance().populateObjectMap("", getSelectedObjects());

    final HyperlinkActivatedListener hyperlinkListener = this;

    runInBackgroundThread(new Runnable() {
        public void run() {
            // Retrieve details of objects for download
            if (!retrieveObjectsDetails(getSelectedObjects())) {
                return;
            }

            try {
                final FileComparerResults comparisonResults = compareRemoteAndLocalFiles(objectKeyToFilepathMap,
                        s3DownloadObjectsMap);

                DownloadPackage[] downloadPackages = buildDownloadPackageList(comparisonResults,
                        s3DownloadObjectsMap);
                if (downloadPackages == null) {
                    return;
                }

                s3ServiceMulti.downloadObjects(currentSelectedBucket, downloadPackages);

            } catch (final Exception e) {
                runInDispatcherThreadImmediately(new Runnable() {
                    public void run() {
                        String message = "Unable to download objects";
                        log.error(message, e);
                        ErrorDialog.showDialog(ownerFrame, hyperlinkListener, message, e);
                    }
                });
            }
        }
    });
}