Example usage for javax.swing JFileChooser showOpenDialog

List of usage examples for javax.swing JFileChooser showOpenDialog

Introduction

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

Prototype

public int showOpenDialog(Component parent) throws HeadlessException 

Source Link

Document

Pops up an "Open File" file chooser dialog.

Usage

From source file:edu.harvard.i2b2.patientMapping.ui.PatientMappingJPanel.java

private String getKey() {
    String path = null;/*w  w  w .j av a2 s  .  co m*/
    key = UserInfoBean.getInstance().getKey();
    if (key == null) {
        if ((path = getNoteKeyDrive()) == null) {
            Object[] possibleValues = { "Type in the key", "Browse to find the file containing the key" };
            String selectedValue = (String) JOptionPane.showInputDialog(this,

                    "The data you have selected to view contains protected \n"
                            + "health information and has been encrypted.\n"
                            + "In order to view this information you must enter \n"
                            + "the decryption key for this project. \n"
                            + "The key can be entered by either manually entering \n"
                            + "the key or selecting the file that contains the key.",
                    "Decryption Key", JOptionPane.QUESTION_MESSAGE, null, possibleValues, possibleValues[0]);
            if (selectedValue == null) {
                return "canceled";
            }
            if (selectedValue.equalsIgnoreCase("Type in the key")) {
                key = JOptionPane.showInputDialog(this, "Please input the decryption key");
                if (key == null) {
                    return "canceled";
                }
            } else {
                JFileChooser chooser = new JFileChooser();
                int returnVal = chooser.showOpenDialog(this);
                if (returnVal == JFileChooser.CANCEL_OPTION) {
                    return "canceled";
                }

                File f = null;
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    f = chooser.getSelectedFile();
                    System.out.println("Open this file: " + f.getAbsolutePath());

                    BufferedReader in = null;
                    try {
                        in = new BufferedReader(new FileReader(f.getAbsolutePath()));
                        String line = null;
                        while ((line = in.readLine()) != null) {
                            if (line.length() > 0) {
                                key = line.substring(line.indexOf("\"") + 1, line.lastIndexOf("\""));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (in != null) {
                            try {
                                in.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        } else {
            System.out.println("Found key file: " + path);
            BufferedReader in = null;
            try {
                in = new BufferedReader(new FileReader(path));
                String line = null;
                while ((line = in.readLine()) != null) {
                    if (line.length() > 0) {
                        key = line.substring(line.indexOf("\"") + 1, line.lastIndexOf("\""));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    if (key == null) {
        return null;
    } else {
        UserInfoBean.getInstance().setKey(key);
    }
    return key;
}

From source file:com.xyphos.vmtgen.GUI.java

private String selectVTF() {
    JFileChooser fc = new JFileChooser(txtWorkFolder.getText());
    fc.setAcceptAllFileFilterUsed(false);
    fc.setFileFilter(new FileFilterVTF());
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

    int result = fc.showOpenDialog(this);
    if (JFileChooser.APPROVE_OPTION == result) {
        String file = fc.getSelectedFile().getName();
        return FilenameUtils.separatorsToUnix(FilenameUtils.concat(basePath, FilenameUtils.getBaseName(file)))
                .replaceFirst("/", "");
    }/*ww w.j  a v a2 s.  co  m*/

    return null;
}

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// ww  w.  j  av a2s .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.dfki.av.sudplan.ui.MainFrame.java

private void miOpenDataActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miOpenDataActionPerformed
    try {//from w  ww .  j  a va 2s  .com
        String cmd = evt.getActionCommand();
        final JFileChooser fc = new JFileChooser();

        FileFilter fileFilter;
        // Set file filter..
        if (cmd.equalsIgnoreCase(miOpenKMLFile.getActionCommand())) {
            fileFilter = new FileNameExtensionFilter("KML/KMZ File", "kml", "kmz");
        } else if (cmd.equalsIgnoreCase(miAddGeoTiff.getActionCommand())) {
            fileFilter = new FileNameExtensionFilter("GeoTiff File ( *.tif, *.tiff)", "tif", "tiff");
        } else if (cmd.equalsIgnoreCase(miAddShape.getActionCommand())) {
            fileFilter = new FileNameExtensionFilter("ESRI Shapefile (*.shp)", "shp", "SHP");
        } else if (cmd.equalsIgnoreCase(miAddShapeZip.getActionCommand())) {
            fileFilter = new FileNameExtensionFilter("ESRI Shapefile ZIP (*.zip)", "zip", "ZIP");
        } else {
            log.warn("No valid action command.");
            fileFilter = null;
        }
        fc.setFileFilter(fileFilter);

        // Set latest working directory...
        XMLConfiguration xmlConfig = Configuration.getXMLConfiguration();
        String path = xmlConfig.getString("sudplan3D.working.dir");
        File dir;
        if (path != null) {
            dir = new File(path);
            if (dir.exists()) {
                fc.setCurrentDirectory(dir);
            }
        }

        // Show dialog...
        int ret = fc.showOpenDialog(this);

        // Save currently selected working directory...
        dir = fc.getCurrentDirectory();
        path = dir.getAbsolutePath();
        xmlConfig.setProperty("sudplan3D.working.dir", path);

        if (ret != JFileChooser.APPROVE_OPTION) {
            return;
        }

        if (cmd.equalsIgnoreCase(miOpenKMLFile.getActionCommand())) {
            wwPanel.addKMLLayer(fc.getSelectedFile());
        } else if (cmd.equalsIgnoreCase(miAddGeoTiff.getActionCommand())) {
            wwPanel.addGeoTiffLayer(fc.getSelectedFile());
        } else if (cmd.equalsIgnoreCase(miAddShape.getActionCommand())
                || cmd.equalsIgnoreCase(miAddShapeZip.getActionCommand())) {
            IVisAlgorithm algo = VisAlgorithmFactory.newInstance(VisPointCloud.class.getName());
            if (algo != null) {
                wwPanel.addLayer(fc.getSelectedFile(), algo, null);
            } else {
                log.error("VisAlgorithm {} not supported.", VisPointCloud.class.getName());
                JOptionPane.showMessageDialog(this, "Algorithm not supported.", "Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        } else {
            log.warn("No valid action command.");
        }
    } catch (Exception ex) {
        log.error(ex.toString());
        JOptionPane.showMessageDialog(this, ex.toString(), "Error", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.jug.MoMA.java

/**
 * Shows a JFileChooser set up to accept the selection of folders. If
 * 'cancel' is pressed this method terminates the MotherMachine app.
 *
 * @param guiFrame//from  w w w .  ja  v a2 s .  c om
 *            parent frame
 * @param path
 *            path to the folder to open initially
 * @return an instance of {@link File} pointing at the selected folder.
 */
private File showFolderChooser(final JFrame guiFrame, final String path) {
    File selectedFile = null;

    if (SystemUtils.IS_OS_MAC) {
        // --- ON MAC SYSTEMS --- ON MAC SYSTEMS --- ON MAC SYSTEMS --- ON MAC SYSTEMS --- ON MAC SYSTEMS ---
        System.setProperty("apple.awt.fileDialogForDirectories", "true");
        final FileDialog fd = new FileDialog(guiFrame, "Select folder containing image sequence...",
                FileDialog.LOAD);
        fd.setDirectory(path);
        //         fd.setLocation(50,50);
        fd.setVisible(true);
        selectedFile = new File(fd.getDirectory() + "/" + fd.getFile());
        if (fd.getFile() == null) {
            System.exit(0);
            return null;
        }
        System.setProperty("apple.awt.fileDialogForDirectories", "false");
    } else {
        // --- NOT ON A MAC --- NOT ON A MAC --- NOT ON A MAC --- NOT ON A MAC --- NOT ON A MAC --- NOT ON A MAC ---
        final JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File(path));
        chooser.setDialogTitle("Select folder containing image sequence...");
        chooser.setFileFilter(new FileFilter() {

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

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

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

    return selectedFile;
}

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(//  w w w .  jav a 2s. c om
            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:GUI.PizzaCat.java

private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
    JFileChooser chooser = new JFileChooser("");
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    int returnVal = chooser.showOpenDialog((java.awt.Component) null);

    if (returnVal == JFileChooser.APPROVE_OPTION) {

        java.io.File inFile;/*from   w  w  w .jav a2  s. c o m*/
        inFile = chooser.getSelectedFile();
        String path;
        path = inFile.getAbsolutePath();
        jTextPane1.setText(path);
        //processFile(inFile);
    }
}

From source file:FirstStatMain.java

private void btnattachmentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnattachmentActionPerformed
    JFileChooser jch = new JFileChooser();
    jch.showOpenDialog(null);

    File imgfile = jch.getSelectedFile();
    file_path = imgfile.getAbsolutePath();
    attachmentpath.setText(file_path);//from  w  w  w. j av  a  2s  .  c  o m
    txtattachmentname.setText(file_path);
}

From source file:FirstStatMain.java

private void btnDocAttachActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDocAttachActionPerformed
    JFileChooser jch = new JFileChooser();
    jch.showOpenDialog(null);

    File imgfile = jch.getSelectedFile();
    String Docfile_path = imgfile.getAbsolutePath();
    txtDocattach.setText(Docfile_path);/*from w  ww.  jav a2s  .  c om*/

}

From source file:com.sshtools.sshterm.SshTermSessionPanel.java

/**
 *
 *
 * @param event//from   www. j av  a  2  s . c o  m
 */
public void actionPerformed(ActionEvent event) {
    // Get the name of the action command
    String command = event.getActionCommand();

    if ((stopAction != null) && command.equals(stopAction.getActionCommand())) {
        stopRecording();
    }

    if ((recordAction != null) && command.equals(recordAction.getActionCommand())) {
        //  We need to go back to windowed mode if in full screen mode
        setFullScreenMode(false);

        // Select the file to record to
        JFileChooser fileDialog = new JFileChooser(System.getProperty("user.home"));
        int ret = fileDialog.showSaveDialog(this);

        if (ret == fileDialog.APPROVE_OPTION) {
            recordingFile = fileDialog.getSelectedFile();

            if (recordingFile.exists()
                    && (JOptionPane.showConfirmDialog(this, "File exists. Are you sure?", "File exists",
                            JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION)) {
                return;
            }

            try {
                recordingOutputStream = new FileOutputStream(recordingFile);
                statusBar.setStatusText("Recording to " + recordingFile.getName());
                setAvailableActions();
            } catch (IOException ioe) {
                showExceptionMessage("Error", "Could not open file for recording\n\n" + ioe.getMessage());
            }
        }
    }

    if ((playAction != null) && command.equals(playAction.getActionCommand())) {
        //  We need to go back to windowed mode if in full screen mode
        setFullScreenMode(false);

        // Select the file to record to
        JFileChooser fileDialog = new JFileChooser(System.getProperty("user.home"));
        int ret = fileDialog.showOpenDialog(this);

        if (ret == fileDialog.APPROVE_OPTION) {
            File playingFile = fileDialog.getSelectedFile();
            InputStream in = null;

            try {
                statusBar.setStatusText("Playing from " + playingFile.getName());
                in = new FileInputStream(playingFile);

                byte[] b = null;
                int a = 0;

                while (true) {
                    a = in.available();

                    if (a == -1) {
                        break;
                    }

                    if (a == 0) {
                        a = 1;
                    }

                    b = new byte[a];
                    a = in.read(b);

                    if (a == -1) {
                        break;
                    }

                    //emulation.write(b);
                    emulation.getOutputStream().write(b);
                }

                statusBar.setStatusText("Finished playing " + playingFile.getName());
                setAvailableActions();
            } catch (IOException ioe) {
                statusBar.setStatusText("Error playing " + playingFile.getName());
                showExceptionMessage("Error", "Could not open file for playback\n\n" + ioe.getMessage());
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException ioe) {
                        log.error(ioe);
                    }
                }
            }
        }
    }

    if ((closeAction != null) && command.equals(closeAction.getActionCommand())) {
        closeSession();
    }
}