Example usage for javax.swing JFileChooser setFileSelectionMode

List of usage examples for javax.swing JFileChooser setFileSelectionMode

Introduction

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

Prototype

@BeanProperty(preferred = true, enumerationValues = { "JFileChooser.FILES_ONLY",
        "JFileChooser.DIRECTORIES_ONLY",
        "JFileChooser.FILES_AND_DIRECTORIES" }, description = "Sets the types of files that the JFileChooser can choose.")
public void setFileSelectionMode(int mode) 

Source Link

Document

Sets the JFileChooser to allow the user to just select files, just select directories, or select both files and directories.

Usage

From source file:grupob.TipoProceso.java

private void seleccionarFirmasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_seleccionarFirmasActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    fileChooser.setDialogTitle("Seleccionar Carpeta");
    int returnValue = fileChooser.showOpenDialog(null);
    if (returnValue == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        if (!Utils.validarRutaImagenHuella(selectedFile.getAbsolutePath(), 1)) {
            JOptionPane.showMessageDialog(null,
                    "Debe seleccionar una carpeta con archivos JPG con la cantidad de registros de votantes exacta.");
        } else {/*  w  w  w.j  a v a  2 s  .  com*/
            textConfFirmas.setText("" + selectedFile);
        }
        //            Recorte.rutaFirma=""+selectedFile;            
    }
}

From source file:SimpleFileChooser.java

public SimpleFileChooser() {
    super("File Chooser Test Frame");
    setSize(350, 200);//  w ww. j  a  v a 2  s .  c om
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    Container c = getContentPane();
    c.setLayout(new FlowLayout());

    JButton openButton = new JButton("Open");
    JButton saveButton = new JButton("Save");
    JButton dirButton = new JButton("Pick Dir");
    final JLabel statusbar = new JLabel("Output of your selection will go here");

    // Create a file chooser that opens up as an Open dialog
    openButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(true);
            int option = chooser.showOpenDialog(SimpleFileChooser.this);
            if (option == JFileChooser.APPROVE_OPTION) {
                File[] sf = chooser.getSelectedFiles();
                String filelist = "nothing";
                if (sf.length > 0)
                    filelist = sf[0].getName();
                for (int i = 1; i < sf.length; i++) {
                    filelist += ", " + sf[i].getName();
                }
                statusbar.setText("You chose " + filelist);
            } else {
                statusbar.setText("You canceled.");
            }
        }
    });

    // Create a file chooser that opens up as a Save dialog
    saveButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            int option = chooser.showSaveDialog(SimpleFileChooser.this);
            if (option == JFileChooser.APPROVE_OPTION) {
                statusbar.setText("You saved "
                        + ((chooser.getSelectedFile() != null) ? chooser.getSelectedFile().getName()
                                : "nothing"));
            } else {
                statusbar.setText("You canceled.");
            }
        }
    });

    // Create a file chooser that allows you to pick a directory
    // rather than a file
    dirButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int option = chooser.showOpenDialog(SimpleFileChooser.this);
            if (option == JFileChooser.APPROVE_OPTION) {
                statusbar.setText("You opened "
                        + ((chooser.getSelectedFile() != null) ? chooser.getSelectedFile().getName()
                                : "nothing"));
            } else {
                statusbar.setText("You canceled.");
            }
        }
    });

    c.add(openButton);
    c.add(saveButton);
    c.add(dirButton);
    c.add(statusbar);
}

From source file:fur.shadowdrake.minecraft.InstallPanel.java

private void browseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseActionPerformed
    JFileChooser fc = new JFileChooser(new File(dirBox.getText()));

    fc.setFileHidingEnabled(false);//from   www .  j a v  a  2s. co m
    fc.setDialogTitle("Select directory");
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    if (fc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        dirBox.setText(fc.getSelectedFile().toString());
    }
}

From source file:edu.ku.brc.specify.tools.StrLocalizerApp.java

/**
 * New language 'project'//from   www .  j a v  a  2s.c  o m
 */
protected void doNewLocale() {
    if (!checkForChanges()) {
        return;
    }

    ChooseFromListDlg<LanguageEntry> ldlg = new ChooseFromListDlg<LanguageEntry>((Frame) getTopWindow(),
            getResourceString("StrLocalizerApp.ChooseLanguageDlgTitle"), languages);
    UIHelper.centerAndShow(ldlg);
    if (ldlg.isCancelled() || ldlg.getSelectedObject() == null) {
        return;
    }

    JFileChooser fdlg = new JFileChooser();
    fdlg.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int fdlgResult = fdlg.showOpenDialog(null);
    if (fdlgResult != JFileChooser.APPROVE_OPTION) {
        return;
    }

    File destDir = fdlg.getSelectedFile();

    destLanguage = ldlg.getSelectedObject();
    final String newLang = destLanguage.getEnglishName();
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            destLbl.setText(newLang + ":");
        }
    });

    setupSrcFiles(getDefaultPath());
    setupDestFiles(ldlg.getSelectedObject().getCode(), destDir.getPath());

    for (StrLocaleFile file : destFiles) {
        file.save();
    }
    currentPath = destDir.getPath();
    newSrcFile(getResourcesFile());
}

From source file:mondrian.gui.Workbench.java

private void openMenuItemActionPerformed(ActionEvent evt) {
    JFileChooser jfc = new JFileChooser();
    try {/*from   w  w  w.  ja va 2 s  . c om*/
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.setFileFilter(new javax.swing.filechooser.FileFilter() {
            public boolean accept(File pathname) {
                return pathname.getName().toLowerCase().endsWith(".xml") || pathname.isDirectory();
            }

            public String getDescription() {
                return getResourceConverter().getString("workbench.open.schema.file.type",
                        "Mondrian Schema files (*.xml)");
            }
        });

        String lastUsed = getWorkbenchProperty(LAST_USED1_URL);

        if (lastUsed != null) {
            jfc.setCurrentDirectory(new File(new URI(lastUsed)));
        }
    } catch (Exception ex) {
        LOGGER.error("Could not set file chooser", ex);
    }
    MondrianProperties.instance();
    if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        try {
            setLastUsed(jfc.getSelectedFile().getName(), jfc.getSelectedFile().toURI().toURL().toString());
        } catch (MalformedURLException e) {
            LOGGER.error(e);
        }

        openSchemaFrame(jfc.getSelectedFile(), false);
    }
}

From source file:net.rptools.maptool.launcher.MapToolLauncher.java

private JPanel buildBasicPanel() {
    final JPanel p = new JPanel();
    p.setLayout(new BorderLayout());

    // BASIC:  Top panel
    final JPanel logoPanel = new JPanel();
    logoPanel.setLayout(new FlowLayout());
    logoPanel.setBorder(//from w w  w  .  j  ava2s. c  o  m
            new TitledBorder(new LineBorder(Color.BLACK), CopiedFromOtherJars.getText("msg.logoPanel.border"))); //$NON-NLS-1$

    jlMTLogo.setIcon(icon);
    logoPanel.add(jlMTLogo);

    // BASIC:  Middle panel
    final JPanel memPanel = new JPanel();
    memPanel.setLayout(new GridLayout(3, 2));
    memPanel.setBorder(new LineBorder(Color.WHITE));

    jtfMaxMem.setHorizontalAlignment(SwingConstants.RIGHT);
    jtfMaxMem.setInfo(CopiedFromOtherJars.getText("msg.info.javaMaxMem", DEFAULT_MAXMEM)); //$NON-NLS-1$ 
    jtfMaxMem.setToolTipText(CopiedFromOtherJars.getText("msg.tooltip.javaMaxMem")); //$NON-NLS-1$
    jtfMaxMem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            jtfMaxMemActionPerformed(evt);
        }
    });
    jtfMaxMem.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent evt) {
            jtfMaxMemFocusLost(evt);
        }

        @Override
        public void focusGained(FocusEvent evt) {
            jtfMaxMemFocusLost(evt);
        }
    });
    jtfMaxMem.addKeyListener(new InputValidator());

    jtfMinMem.setHorizontalAlignment(SwingConstants.RIGHT);
    jtfMinMem.setInfo(CopiedFromOtherJars.getText("msg.info.javaMinMem", DEFAULT_MINMEM)); //$NON-NLS-1$ 
    jtfMinMem.setToolTipText(CopiedFromOtherJars.getText("msg.tooltip.javaMinMem")); //$NON-NLS-1$
    jtfMinMem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            jtfMinMemActionPerformed(evt);
        }
    });
    jtfMinMem.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent evt) {
            jtfMinMemFocusLost(evt);
        }

        @Override
        public void focusGained(FocusEvent evt) {
            jtfMinMemFocusLost(evt);
        }
    });
    jtfMinMem.addKeyListener(new InputValidator());

    jtfStackSize.setHorizontalAlignment(SwingConstants.RIGHT);
    jtfStackSize.setInfo(CopiedFromOtherJars.getText("msg.info.javaStackSize", DEFAULT_STACKSIZE)); //$NON-NLS-1$ 
    jtfStackSize.setToolTipText(CopiedFromOtherJars.getText("msg.tooltip.javaStackSize")); //$NON-NLS-1$
    jtfStackSize.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            jtfStackSizeActionPerformed(evt);
        }
    });
    jtfStackSize.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent evt) {
            jtfStackSizeFocusLost(evt);
        }

        @Override
        public void focusGained(FocusEvent evt) {
            jtfStackSizeFocusLost(evt);
        }
    });
    jtfStackSize.addKeyListener(new InputValidator());

    memPanel.add(jtfMaxMem);
    memPanel.add(jtfMinMem);
    memPanel.add(jtfStackSize);

    // BASIC:  Bottom panel
    final JPanel southPanel = new JPanel();
    southPanel.setLayout(new BorderLayout());

    final JPanel cbPanel = new JPanel();
    cbPanel.setLayout(new GridLayout(2, 1));
    cbPanel.setBorder(new LineBorder(Color.GRAY));

    jcbPromptUser.setSelected(true);
    jcbPromptUser.setText(CopiedFromOtherJars.getText("msg.info.promptAtNextLaunch")); //$NON-NLS-1$
    jcbPromptUser.setToolTipText(CopiedFromOtherJars.getText("msg.tooltip.promptAtNextLaunch")); //$NON-NLS-1$
    jcbPromptUser.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            promptUser = jcbPromptUser.isSelected();
        }
    });

    jbMTJar.setText(jbMTJarText);
    jbMTJar.setToolTipText(CopiedFromOtherJars.getText("msg.tooltip.registerMapToolJar")); //$NON-NLS-1$
    jbMTJar.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final JFileChooser jfc = new JFileChooser();
            jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
            FileFilter filter = new FileNameExtensionFilter(
                    CopiedFromOtherJars.getText("msg.chooser.javaExecutable"), "jar"); //$NON-NLS-1$ //$NON-NLS-2$
            jfc.addChoosableFileFilter(filter);
            jfc.setFileFilter(filter);
            if (IS_MAC) {
                filter = new FileNameExtensionFilter(
                        CopiedFromOtherJars.getText("msg.chooser.appleApplicationBundle"), "app"); //$NON-NLS-1$ //$NON-NLS-2$
                jfc.addChoosableFileFilter(filter);
            }
            jfc.setCurrentDirectory(mapToolJarDir);

            final int returnVal = jfc.showOpenDialog(jbMTJar);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                final File f = jfc.getSelectedFile();
                final String fileName = f.getName();
                if (IS_MAC && fileName.endsWith(".app")) { //$NON-NLS-1$
                    File jarDir = new File(f.getParentFile(), fileName);
                    if (jarDir.isDirectory()) {
                        jarDir = new File(jarDir, "Contents/Resources/Java"); //$NON-NLS-1$
                        if (jarDir.isDirectory()) {
                            mapToolJarDir = jarDir;
                            mapToolJarName = fileName.replace(".app", ".jar"); //$NON-NLS-1$ //$NON-NLS-2$
                        } else {
                            logMsg(Level.SEVERE,
                                    "{0} does not contain 'Contents/Resources/Java' like it should!", //$NON-NLS-1$
                                    "msg.chooser.badAppLocation", jarDir); //$NON-NLS-1$
                            return;
                        }
                    } else {
                        logMsg(Level.SEVERE, "{0} is not a directory and it should be!", //$NON-NLS-1$
                                "msg.chooser.badAppLocation", jarDir); //$NON-NLS-1$
                        return;
                    }
                } else {
                    mapToolJarName = fileName;
                    mapToolJarDir = f.getParentFile();
                }
                logMsg(Level.INFO, f.toString(), null);
                jbMTJar.setText(fileName.replace(".jar", EMPTY)); //$NON-NLS-1$
                if (fileName.toLowerCase().startsWith("maptool-")) {
                    // We expect the name matches 'maptool-1.3.b89.jar'
                    mapToolVersion = " " + fileName.substring(8, 11);
                } else {
                    logMsg(Level.SEVERE, "Cannot determine MapTool version number from JAR filename: {0}", //$NON-NLS-1$
                            "msg.info.noMapToolVersion", fileName);
                    mapToolVersion = EMPTY;
                }
                jbLaunch.setEnabled(true);
                updateCommand();
                jbLaunch.requestFocusInWindow();
            }
        }
    });

    cbPanel.add(jcbPromptUser);
    cbPanel.add(jbMTJar);

    southPanel.add(cbPanel, BorderLayout.CENTER);

    p.add(memPanel, BorderLayout.CENTER);
    p.add(logoPanel, BorderLayout.NORTH);
    p.add(southPanel, BorderLayout.SOUTH);
    p.setBorder(new LineBorder(Color.BLACK));
    return p;
}

From source file:model.settings.ReadSettings.java

/**
 * checks whether program information on current workspace exist.
 * @return if workspace is now set.//from ww w . j av a 2  s .  c o m
 */
public static String install() {
    boolean installed = false;
    String wsLocation = "";
    /*
     * does program root directory exist?
     */
    if (new File(PROGRAM_LOCATION).exists()) {

        //try to read 
        try {
            wsLocation = readFromFile(PROGRAM_SETTINGS_LOCATION);

            installed = new File(wsLocation).exists();
            if (!installed) {
                wsLocation = "";
            }

        } catch (FileNotFoundException e) {
            System.out.println("file not found " + e);
            showErrorMessage();
        } catch (IOException e) {
            System.out.println("io" + e);
            showErrorMessage();
        }
    }

    //if settings not found.
    if (!installed) {

        new File(PROGRAM_LOCATION).mkdir();
        try {

            //create new file chooser
            JFileChooser jc = new JFileChooser();

            //sets the text and language of all the components in JFileChooser
            UIManager.put("FileChooser.openDialogTitleText", "Open");
            UIManager.put("FileChooser.lookInLabelText", "LookIn");
            UIManager.put("FileChooser.openButtonText", "Open");
            UIManager.put("FileChooser.cancelButtonText", "Cancel");
            UIManager.put("FileChooser.fileNameLabelText", "FileName");
            UIManager.put("FileChooser.filesOfTypeLabelText", "TypeFiles");
            UIManager.put("FileChooser.openButtonToolTipText", "OpenSelectedFile");
            UIManager.put("FileChooser.cancelButtonToolTipText", "Cancel");
            UIManager.put("FileChooser.fileNameHeaderText", "FileName");
            UIManager.put("FileChooser.upFolderToolTipText", "UpOneLevel");
            UIManager.put("FileChooser.homeFolderToolTipText", "Desktop");
            UIManager.put("FileChooser.newFolderToolTipText", "CreateNewFolder");
            UIManager.put("FileChooser.listViewButtonToolTipText", "List");
            UIManager.put("FileChooser.newFolderButtonText", "CreateNewFolder");
            UIManager.put("FileChooser.renameFileButtonText", "RenameFile");
            UIManager.put("FileChooser.deleteFileButtonText", "DeleteFile");
            UIManager.put("FileChooser.filterLabelText", "TypeFiles");
            UIManager.put("FileChooser.detailsViewButtonToolTipText", "Details");
            UIManager.put("FileChooser.fileSizeHeaderText", "Size");
            UIManager.put("FileChooser.fileDateHeaderText", "DateModified");
            SwingUtilities.updateComponentTreeUI(jc);

            jc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            jc.setMultiSelectionEnabled(false);

            final String informationMsg = "Please select the workspace folder. \n"
                    + "By default, the new files are saved in there. \n\n"
                    + "Is changed simply by using the Save-As option.\n"
                    + "If no folder is specified, the default worspace folder \n"
                    + "is the home directory of the current user.";
            final int response = JOptionPane.showConfirmDialog(jc, informationMsg, "Select workspace folder",
                    JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE);

            final String defaultSaveLocation = System.getProperty("user.home")
                    + System.getProperty("file.separator");
            File f;
            if (response != JOptionPane.NO_OPTION) {

                //fetch selected file
                f = jc.getSelectedFile();
                jc.showDialog(null, "select");
            } else {
                f = new File(defaultSaveLocation);
            }

            printInformation();

            if (f == null) {
                f = new File(defaultSaveLocation);
            }
            //if file selected
            if (f != null) {

                //if the file exists
                if (f.exists()) {
                    writeToFile(PROGRAM_SETTINGS_LOCATION, ID_PROGRAM_LOCATION + "\n" + f.getAbsolutePath());
                } else {

                    //open message dialog
                    JOptionPane.showConfirmDialog(null, "Folder does " + "not exist",
                            "Error creating workspace", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE,
                            null);
                }

                //recall install
                return install();
            }

        } catch (IOException e) {
            System.out.println(e);
            JOptionPane.showConfirmDialog(null, "An exception occured." + " Try again later.",
                    "Error creating workspace", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null);
        }
    }

    if (System.getProperty("os.name").equals("Mac OS X")) {

        installOSX();
    } else if (System.getProperty("os.name").equals("Linux")) {
        installLinux();
    } else if (System.getProperty("os.name").equals("Windows")) {
        installWindows();
    }

    return wsLocation;

}

From source file:com.archivas.clienttools.arcmover.gui.panels.ProfilePanel.java

private String browseDirectory() {
    if (getSelectedProfile() != FileSystemProfile.LOCAL_FILESYSTEM_PROFILE) {
        // browse only supported on LFS
        return null;
    }/*from w  w  w .ja  v  a2 s  .c  om*/

    String loadPath = currentDir.getPath();
    JFileChooser chooser = new JFileChooser(loadPath);
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    int retVal = chooser.showOpenDialog(this);
    if (retVal == JFileChooser.APPROVE_OPTION) {
        return chooser.getSelectedFile().getAbsolutePath();
    } else {
        return null;
    }
}

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);
                                }//  w  w  w  .j  ava2s . co  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:org.fhaes.fhsamplesize.view.FHSampleSize.java

/**
 * Open a JFileChooser and return the file that the user specified for saving. Takes a parameter that specifies the type of file. Either
 * TAB or PNG./*w w  w.ja v a  2  s  . c om*/
 * 
 * @return
 */
private File getFileFromSaveDialog(String fileTypeToSave) {

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

    if (fileTypeToSave == "TAB") {
        TABFilter filterTAB = new TABFilter();
        fc.addChoosableFileFilter(filterTAB);
        fc.setFileFilter(filterTAB);
        fc.setDialogTitle("Export table as text file...");

    } else if (fileTypeToSave == "PDF") {
        PDFFilter filterPDF = new PDFFilter();
        fc.addChoosableFileFilter(filterPDF);
        fc.setFileFilter(filterPDF);
        fc.setDialogTitle("Export chart as PDF...");
    }

    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setMultiSelectionEnabled(false);

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

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

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

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

    if (outputFile.exists()) {
        Object[] options = { "Overwrite", "No", "Cancel" };

        // notes about parameters: null (don't use custom icon), options (the titles of buttons), options[0] (default button title)
        int response = JOptionPane.showOptionDialog(App.mainFrame,
                "The file '" + outputFile.getName() + "' already exists.  Are you sure you want to overwrite?",
                "Confirm", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options,
                options[0]);

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