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:dotaSoundEditor.Controls.EditorPanel.java

protected File promptUserForNewFile(String wavePath) {
    JFileChooser chooser = new JFileChooser(new File(UserPrefs.getInstance().getWorkingDirectory()));
    FileNameExtensionFilter filter = new FileNameExtensionFilter("MP3s and WAVs", "mp3", "wav");
    chooser.setAcceptAllFileFilterUsed((false));
    chooser.setFileFilter(filter);//from   w ww.j  a va  2  s .co  m
    chooser.setMultiSelectionEnabled(false);

    int chooserRetVal = chooser.showOpenDialog(chooser);
    if (chooserRetVal == JFileChooser.APPROVE_OPTION) {
        DefaultMutableTreeNode selectedFile = (DefaultMutableTreeNode) getTreeNodeFromWavePath(wavePath);
        Path chosenFile = Paths.get(chooser.getSelectedFile().getAbsolutePath());
        //Strip caps and spaces out of filenames. The item sound parser seems to have trouble with them.
        String destFileName = chosenFile.getFileName().toString().toLowerCase().replace(" ", "_");
        Path destPath = Paths.get(installDir, "/dota/sound/" + getCustomSoundPathString() + destFileName);
        UserPrefs.getInstance().setWorkingDirectory(chosenFile.getParent().toString());

        try {
            new File(destPath.toString()).mkdirs();
            Files.copy(chosenFile, destPath, StandardCopyOption.REPLACE_EXISTING);

            String waveString = selectedFile.getUserObject().toString();
            int startIndex = -1;
            int endIndex = -1;
            if (waveString.contains("\"wave\"")) {
                startIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 2);
                endIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 3);
            } else //Some wavestrings don't have the "wave" at the beginning for some reason
            {
                startIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 0);
                endIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 1);
            }

            String waveStringFilePath = waveString.substring(startIndex, endIndex + 1);
            waveString = waveString.replace(waveStringFilePath,
                    "\"" + getCustomSoundPathString() + destFileName + "\"");
            selectedFile.setUserObject(waveString);

            //Write out modified tree to scriptfile.
            ScriptParser parser = new ScriptParser(this.currentTreeModel);
            String scriptString = getCurrentScriptString();
            Path scriptPath = Paths.get(scriptString);
            parser.writeModelToFile(scriptPath.toString());

            //Update UI
            ((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent()).setUserObject(waveString);
            ((DefaultTreeModel) currentTree.getModel())
                    .nodeChanged((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent());
            JOptionPane.showMessageDialog(this, "Sound file successfully replaced.");

        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Unable to replace sound.\nDetails: " + ex.getMessage(),
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    return null;
}

From source file:it.staiger.jmeter.protocol.http.config.gui.DynamicFilePanel.java

/**
 * Fills the table with the file parameters from the import settings panel
 *///from   w w  w  .  j a va2s  .co m
private void importFiles() {
    String relPath = folder.getText();
    String replace = relPath + File.separator;
    if (relPath.isEmpty()) {
        relPath = FileDialoger.getLastJFCDirectory();
        replace = "";
    }

    JFileChooser chooser = new JFileChooser(new File(relPath));
    chooser.setMultiSelectionEnabled(true);
    chooser.setDialogTitle("select files");// $NON-NLS-1$

    if (chooser.showOpenDialog(GuiPackage.getInstance().getMainFrame()) == JFileChooser.APPROVE_OPTION) {
        File[] files = chooser.getSelectedFiles();
        for (File file : files) {
            String path = file.getAbsolutePath().replace(replace, "");
            String name = file.getName();
            int last = name.lastIndexOf(".");
            if (last != -1)
                name = name.substring(0, last);

            HTTPFileArg hFile = new HTTPFileArg(path, name, attachmentsCT.getText());

            addFile(hFile);
        }
        FileDialoger.setLastJFCDirectory(files[0].getAbsolutePath());
    }

}

From source file:pl.dpbz.poid.zadanie3.GUI.java

private String readSoundFile() {
    final JFileChooser fc = new JFileChooser();
    fc.setAcceptAllFileFilterUsed(false);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("WAV sounds", "wav");
    fc.addChoosableFileFilter(filter);/*w ww  . j  a  va2s  . c o  m*/
    int returnVal = fc.showOpenDialog(this);
    String path = fc.getSelectedFile().getAbsolutePath();
    System.out.println("path: " + path);

    return path;
}

From source file:com.ejie.uda.jsonI18nEditor.Editor.java

public void showImportDialog() {
    String path = null;/*from w w  w . j a  va  2 s  . c  om*/
    if (resourcesDir != null) {
        path = resourcesDir.toString();
    }
    JFileChooser fc = new JFileChooser(path);
    fc.setDialogTitle(MessageBundle.get("dialogs.import.title"));
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setFileFilter(new FileNameExtensionFilter("json i18n file", "json"));
    int result = fc.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
        importResources(Paths.get(fc.getSelectedFile().getPath()));
    }
}

From source file:fll.subjective.SubjectiveFrame.java

/**
 * Prompt the user for a file./*from  w  w w.j a  va2 s .c o  m*/
 * 
 * @param title the title on the chooser dialog
 * @return the file if accepted, null if canceled
 */
private File chooseSubjectiveFile(final String title) {
    final File initialDirectory = getInitialDirectory();
    final JFileChooser fileChooser = new JFileChooser(initialDirectory);
    fileChooser.setDialogTitle(title);
    fileChooser.setFileFilter(new BasicFileFilter("FLL Subjective Data Files", "fll"));
    final int state = fileChooser.showOpenDialog(this);
    if (JFileChooser.APPROVE_OPTION == state) {
        final File file = fileChooser.getSelectedFile();
        setInitialDirectory(file);
        return file;
    } else {
        return null;
    }
}

From source file:DOMTreeTest.java

/**
     * Open a file and load the document.
     *//*from  w  ww  .  j a  v  a2 s .c  o m*/
    public void openFile() {
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));

        chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml");
            }

            public String getDescription() {
                return "XML files";
            }
        });
        int r = chooser.showOpenDialog(this);
        if (r != JFileChooser.APPROVE_OPTION)
            return;
        final File file = chooser.getSelectedFile();

        new SwingWorker<Document, Void>() {
            protected Document doInBackground() throws Exception {
                if (builder == null) {
                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    builder = factory.newDocumentBuilder();
                }
                return builder.parse(file);
            }

            protected void done() {
                try {
                    Document doc = get();
                    JTree tree = new JTree(new DOMTreeModel(doc));
                    tree.setCellRenderer(new DOMTreeCellRenderer());

                    setContentPane(new JScrollPane(tree));
                    validate();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(DOMTreeFrame.this, e);
                }
            }
        }.execute();
    }

From source file:localization.SplitterUI.java

private void browseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseActionPerformed
    // TODO add your handling code here:
    JFileChooser chooser = new JFileChooser();
    chooser.showOpenDialog(null);
    File f = chooser.getSelectedFile();
    String filename = f.getAbsolutePath();
    if (filename.endsWith(".lpu") || filename.endsWith(".zip")) {
        filepath.setText(filename);/*from w  w w  .jav  a 2 s .  c o  m*/
    } else {
        JOptionPane.showMessageDialog(this, "The file type you select is not correct. ", "Upload File Issue",
                JOptionPane.ERROR_MESSAGE, null);
        return;
    }
}

From source file:org.apache.jmeter.visualizers.CreateReport.java

@Override
public void actionPerformed(ActionEvent ev) {
    /*/*  w  w w  . j a va2s.com*/
     if(ev.equals(SAVEASCSV))
      {
         saveAsCsv.setSelected(true);
      }
      else if (ev.equals(SAVEASPDF)
      {
         saveAsPdf.setSelected(true);
      }
     */

    String action = ev.getActionCommand();

    if (action.equals(BROWSE)) {

        JFileChooser j = new JFileChooser();
        j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = j.showOpenDialog(this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            basepath.setText(j.getSelectedFile().getAbsolutePath());
            BASEPATH = basepath.getText().trim();
            JOptionPane.showMessageDialog(null, "alert", basepath.getText(), JOptionPane.OK_OPTION);

        }
        if (ev.getSource() == saveTable) {
            JFileChooser chooser = FileDialoger.promptToSaveFile("summary.csv");//$NON-NLS-1$
            if (chooser == null) {
                return;
            }
            FileWriter writer = null;
            try {
                writer = new FileWriter(chooser.getSelectedFile());
                CSVSaveService.saveCSVStats(model, writer, saveHeaders.isSelected());
            } catch (FileNotFoundException e) {
                log.warn(e.getMessage());
            } catch (IOException e) {
                log.warn(e.getMessage());
            } finally {
                JOrphanUtils.closeQuietly(writer);
            }
        }
    }

}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopFileUploadField.java

public DesktopFileUploadField() {
    fileUploading = AppBeans.get(FileUploadingAPI.NAME);
    messages = AppBeans.get(Messages.NAME);
    exportDisplay = AppBeans.get(ExportDisplay.NAME);

    ComponentsFactory componentsFactory = AppBeans.get(ComponentsFactory.NAME);
    uploadButton = (Button) componentsFactory.createComponent(Button.NAME);
    final JFileChooser fileChooser = new JFileChooser();
    uploadButton.setAction(new AbstractAction("") {
        @Override//from  w  w w.  j a va2 s . c o  m
        public void actionPerform(Component component) {
            if (fileChooser.showOpenDialog(uploadButton.unwrap(JButton.class)) == JFileChooser.APPROVE_OPTION) {
                uploadFile(fileChooser.getSelectedFile());
            }
        }
    });
    uploadButton.setCaption(messages.getMessage(getClass(), "export.selectFile"));

    initImpl();
}

From source file:ar.edu.uns.cs.vyglab.arq.rockar.gui.JFrameControlPanel.java

private void openTable() {
    this.checkToSave();
    DataCenter.minerals = new HashMap<Integer, Vector<Point>>();
    this.clearJTable();
    try {// w  w  w. j a  v a2s. com
        File currentDir = new File(System.getProperty("user.dir"));
        JFileChooser openDialgo = new JFileChooser(currentDir);
        FileNameExtensionFilter filter = new FileNameExtensionFilter("MTF File", "mtf", "mtf");
        openDialgo.setFileFilter(filter);
        int response = openDialgo.showOpenDialog(this);
        if (response == openDialgo.APPROVE_OPTION) {
            this.openTable(openDialgo.getSelectedFile());
        }
    } catch (Exception e) {

    }
}