Example usage for javax.swing JFileChooser JFileChooser

List of usage examples for javax.swing JFileChooser JFileChooser

Introduction

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

Prototype

public JFileChooser(FileSystemView fsv) 

Source Link

Document

Constructs a JFileChooser using the given FileSystemView.

Usage

From source file:net.chaosserver.timelord.swingui.Timelord.java

/**
 * Persists out the timelord file and allows the user to choose where
 * the file should go./*  w w w .  j  a  va2 s. c  o m*/
 *
 * @param rwClassName the name of the RW class
 *        (e.g. "net.chaosserver.timelord.data.ExcelDataReaderWriter")
 * @param userSelect allows the user to select where the file should
 *        be persisted.
 */
public void writeTimeTrackData(String rwClassName, boolean userSelect) {
    try {
        Class<?> rwClass = Class.forName(rwClassName);
        TimelordDataReaderWriter timelordDataRW = (TimelordDataReaderWriter) rwClass.newInstance();

        int result = JFileChooser.APPROVE_OPTION;
        File outputFile = timelordDataRW.getDefaultOutputFile();

        if (timelordDataRW instanceof TimelordDataReaderWriterUI) {
            TimelordDataReaderWriterUI timelordDataReaderWriterUI = (TimelordDataReaderWriterUI) timelordDataRW;

            timelordDataReaderWriterUI.setParentFrame(applicationFrame);
            JDialog configDialog = timelordDataReaderWriterUI.getConfigDialog();

            configDialog.pack();
            configDialog.setLocationRelativeTo(applicationFrame);
            configDialog.setVisible(true);
        }

        if (userSelect) {
            if (OsUtil.isMac()) {
                FileDialog fileDialog = new FileDialog(applicationFrame, "Select File", FileDialog.SAVE);

                fileDialog.setDirectory(outputFile.getParent());
                fileDialog.setFile(outputFile.getName());
                fileDialog.setVisible(true);
                if (fileDialog.getFile() != null) {
                    outputFile = new File(fileDialog.getDirectory(), fileDialog.getFile());
                }

            } else {
                JFileChooser fileChooser = new JFileChooser(outputFile.getParentFile());

                fileChooser.setSelectedFile(outputFile);
                fileChooser.setFileFilter(timelordDataRW.getFileFilter());
                result = fileChooser.showSaveDialog(applicationFrame);

                if (result == JFileChooser.APPROVE_OPTION) {
                    outputFile = fileChooser.getSelectedFile();
                }
            }
        }

        if (result == JFileChooser.APPROVE_OPTION) {
            timelordDataRW.writeTimelordData(getTimelordData(), outputFile);
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(applicationFrame,
                "Error writing to file.\n" + "Do you have the output file open?", "Save Error",
                JOptionPane.ERROR_MESSAGE, applicationIcon);

        if (log.isErrorEnabled()) {
            log.error("Error persisting file", e);
        }
    }
}

From source file:cs.cirg.cida.CIDAView.java

@Action
public void loadExperiment() {
    JFileChooser chooser = new JFileChooser(experimentController.getDataDirectory());
    FileNameExtensionFilter filter = new FileNameExtensionFilter(CIDAConstants.DIALOG_TXT_CSV_MSG, "txt",
            "csv");
    chooser.setFileFilter(filter);/*from  ww w  .ja  v  a  2s .c o  m*/
    chooser.setMultiSelectionEnabled(true);
    int returnVal = chooser.showOpenDialog(this.getComponent());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        try {
            File[] files = chooser.getSelectedFiles();
            String[] experimentNames = null;
            experimentNames = new String[files.length];
            for (int i = 0; i < files.length; ++i) {
                File dataFile = files[i];
                String tmpName = dataFile.getName().substring(0, dataFile.getName().lastIndexOf("."));
                if (editResultsNameCheckBox.isSelected()) {
                    CIDAInputDialog dialog = new CIDAInputDialog(this.getFrame(),
                            CIDAConstants.RENAME_EXPERIMENT_MSG, tmpName);
                    dialog.displayPrompt();
                    tmpName = dialog.getInput();
                }
                experimentNames[i] = tmpName;
            }
            experimentController.addExperiments(files, experimentNames);
            this.selectExperiment();
        } catch (CIlibIOException ex) {
            CIDAPromptDialog dialog = exceptionController.handleException(this.getFrame(), ex,
                    CIDAConstants.EXCEPTION_OCCURRED);
            dialog.displayPrompt();
        }
    }
}

From source file:avoking.com.documentos.scheduler.startup.Main.java

public void pathsDocs() {
    String userDir = System.getProperty("user.home");

    JOptionPane.showMessageDialog(null, "Ruta para PROCEDIMIENTOS...");
    pathPro = getPathDocs(new JFileChooser(userDir + "/Documents"));

    JOptionPane.showMessageDialog(null, "Ruta para ESPECIFICACIONES...");
    pathEsp = getPathDocs(new JFileChooser(pathPro));

    JOptionPane.showMessageDialog(null, "Ruta para POLITICAS...");
    pathPol = getPathDocs(new JFileChooser(pathEsp));
}

From source file:edu.scripps.fl.pubchem.xmltool.gui.GUIComponent.java

public File fileChooser(JTextField jtf, String ext, String openOrSave) {
    jfcFiles = new JFileChooser(jtf.getText());
    if (!ext.equals(""))
        jfcFiles.addChoosableFileFilter(new MyFileFilter(ext));
    jfcFiles.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    int state;//from   w w  w . j  av a 2 s. c  o  m
    if (openOrSave.equals("open"))
        state = jfcFiles.showOpenDialog(null);
    else
        state = jfcFiles.showSaveDialog(null);

    if (state == JFileChooser.APPROVE_OPTION) {
        File file = checkFileExtension(ext);
        jtf.setText(file.getPath());
        log.info("Opening: " + file.getName() + ".");
        return file;
    } else {
        log.info("Open command cancelled by user.");
        return null;
    }
}

From source file:de.evaluationtool.gui.EvaluationFrameActionListener.java

private void savePositiveNegativeNT() throws IOException {
    JFileChooser chooser = new JFileChooser("Save as multiple nt files. Please choose a directory");
    chooser.setCurrentDirectory(frame.defaultDirectory);
    if (geoFile != null) {
        chooser.setCurrentDirectory(geoFile);
    }/*from w w  w  .j  a  va2  s . c  om*/
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);

    int returnVal = chooser.showSaveDialog(frame);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        frame.savePositiveNegativeNT(chooser.getSelectedFile());
    }
}

From source file:net.sf.profiler4j.console.Console.java

public void openProject() {

    if (client.isConnected()) {
        int ret = JOptionPane.showConfirmDialog(mainFrame, "Proceed and disconnect?", "Open Profiling Project",
                JOptionPane.YES_NO_OPTION);
        if (ret == JOptionPane.NO_OPTION) {
            return;
        }/*from  w  ww.j  av a2  s .  co  m*/
    }

    if (checkUnsavedChanges()) {
        return;
    }

    if (client.isConnected()) {
        disconnect();
        if (client.isConnected()) {
            return;
        }
    }
    JFileChooser fc = new JFileChooser(lastDir);
    fc.addChoosableFileFilter(projectFilter);
    if (fc.showOpenDialog(mainFrame) == JFileChooser.APPROVE_OPTION) {
        File selFile = fc.getSelectedFile();
        SAXBuilder builder = new SAXBuilder();
        Document doc = null;
        try {
            doc = builder.build(selFile);
        } catch (JDOMException e) {
            error("XML Error", e);
        } catch (IOException e) {
            error("I/O Error", e);
        }
        if (doc != null) {
            Project p = new Project();
            Element el = doc.getRootElement();
            p.setHostname(el.getChildText("Host"));
            p.setPort(Integer.parseInt(el.getChildText("Port")));
            Element rulesEl = el.getChild("Rules");

            p.setAccess(Rule.AccessOption.valueOf(rulesEl.getAttributeValue("access")));
            p.setBeanprops(Boolean.parseBoolean(rulesEl.getAttributeValue("beanProps")));

            p.getRules().clear();
            for (Iterator i = rulesEl.getChildren("Rule").iterator(); i.hasNext();) {
                Element r = (Element) i.next();
                Rule rule = new Rule(r.getText(), Rule.Action.valueOf(r.getAttributeValue("action")));
                p.getRules().add(rule);
            }

            // Backwards compatible way to read the export pattern
            // If it is not there, we leave the defaults as they are,
            // otherwise we set the saved setting.
            Element export = el.getChild(PROJECT_XML_ELEMENT__EXPORT_PATTERN);
            if (null != export) {
                String enabled = export.getAttributeValue(PROJECT_XML_ATTRIBUTE__ENABLED);
                p.setExportAutomaticallyEnabled(Boolean.valueOf(enabled));
                p.setExportPattern(export.getAttributeValue(PROJECT_XML_ATTRIBUTE__PATTERN));
            }

            p.setFile(selFile);
            p.clearChanged();
            this.project = p;
            lastDir = selFile.getParentFile();
        }
    }

}

From source file:com.igormaznitsa.ideamindmap.utils.IdeaUtils.java

public static File chooseFile(final Component parent, final boolean filesOnly, final String title,
        final File selectedFile, final FileFilter filter) {
    final JFileChooser chooser = new JFileChooser(selectedFile);

    chooser.setApproveButtonText("Select");
    if (filter != null)
        chooser.setFileFilter(filter);//  w ww  .jav a 2s  . c o  m

    chooser.setDialogTitle(title);
    chooser.setMultiSelectionEnabled(false);

    if (filesOnly)
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    else
        chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    if (chooser.showOpenDialog(parent) == JFileChooser.APPROVE_OPTION) {
        return chooser.getSelectedFile();
    } else {
        return null;
    }
}

From source file:com.jvms.i18neditor.Editor.java

public void showImportDialog() {
    String path = null;//from www  .j a v  a 2s . com
    if (resourcesDir != null) {
        path = resourcesDir.toString();
    }
    JFileChooser fc = new JFileChooser(path);
    fc.setDialogTitle(MessageBundle.get("dialogs.import.title"));
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int result = fc.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
        importResources(Paths.get(fc.getSelectedFile().getPath()));
    }
}

From source file:io.github.jeremgamer.editor.panels.MusicFrame.java

public MusicFrame(JFrame frame, final GeneralSave gs) {

    ArrayList<BufferedImage> icons = new ArrayList<BufferedImage>();
    try {//from   w ww . ja v  a  2s.  c o  m
        icons.add(ImageIO.read(ImageGetter.class.getResource("icon16.png")));
        icons.add(ImageIO.read(ImageGetter.class.getResource("icon32.png")));
        icons.add(ImageIO.read(ImageGetter.class.getResource("icon64.png")));
        icons.add(ImageIO.read(ImageGetter.class.getResource("icon128.png")));
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    this.setIconImages((List<? extends Image>) icons);

    this.setTitle("Musique");
    this.setSize(new Dimension(300, 225));

    this.addWindowListener(new WindowListener() {
        @Override
        public void windowActivated(WindowEvent event) {
        }

        @Override
        public void windowClosed(WindowEvent event) {
        }

        @Override
        public void windowClosing(WindowEvent event) {
            try {
                gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (clip != null) {
                clip.stop();
                clip.close();
                try {
                    audioStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void windowDeactivated(WindowEvent event) {
        }

        @Override
        public void windowDeiconified(WindowEvent event) {
        }

        @Override
        public void windowIconified(WindowEvent event) {
        }

        @Override
        public void windowOpened(WindowEvent event) {
        }
    });

    this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

    content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));

    this.setModal(true);
    this.setLocationRelativeTo(frame);

    JPanel properties = new JPanel();
    properties.setBorder(BorderFactory.createTitledBorder("Lecture"));
    ButtonGroup bg = new ButtonGroup();
    bg.add(one);
    bg.add(loop);
    one.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent event) {
            JRadioButton rb = (JRadioButton) event.getSource();
            if (rb.isSelected()) {
                gs.set("music.reading", 0);
                try {
                    gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (clip != null) {
                    if (clip.isRunning())
                        clip.loop(0);
                }
            }
        }
    });
    loop.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent event) {
            JRadioButton rb = (JRadioButton) event.getSource();
            if (rb.isSelected()) {
                gs.set("music.reading", 1);
                try {
                    gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (clip != null) {
                    if (clip.isRunning())
                        clip.loop(Clip.LOOP_CONTINUOUSLY);
                }
            }
        }
    });
    properties.add(one);
    properties.add(loop);
    if (gs.getInt("music.reading") == 0) {
        one.setSelected(true);
    } else {
        loop.setSelected(true);
    }

    volume.setMaximum(100);
    volume.setMinimum(0);
    volume.setValue(30);
    volume.setPaintTicks(true);
    volume.setPaintLabels(true);
    volume.setMinorTickSpacing(10);
    volume.setMajorTickSpacing(20);
    volume.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent event) {
            JSlider slider = (JSlider) event.getSource();
            double value = slider.getValue();
            gain = value / 100;
            dB = (float) (Math.log(gain) / Math.log(10.0) * 20.0);
            if (clip != null)
                gainControl.setValue(dB);
            gs.set("music.volume", (int) value);
        }
    });
    volume.setValue(gs.getInt("music.volume"));
    properties.add(volume);
    properties.setPreferredSize(new Dimension(300, 125));

    content.add(properties);

    JPanel browsePanel = new JPanel();
    browsePanel.setBorder(BorderFactory.createTitledBorder(""));
    JButton browse = new JButton("Parcourir...");
    if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) {
        preview.setEnabled(false);
        browse.setText("");
        try {
            browse.setIcon(new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    browse.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            JButton button = (JButton) event.getSource();
            if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) {
                if (clip != null) {
                    clip.stop();
                    clip.close();
                    try {
                        audioStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                name.setText("");
                preview.setEnabled(false);
                button.setText("Parcourir...");
                button.setIcon(null);
                new File("projects/" + Editor.getProjectName() + "/music.wav").delete();
                gs.set("music.name", "");
            } else {
                String path = null;
                JFileChooser chooser = new JFileChooser(Editor.lastPath);
                FileNameExtensionFilter filter = new FileNameExtensionFilter("Audio (WAV)", "wav");
                chooser.setFileFilter(filter);
                chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                int option = chooser.showOpenDialog(null);
                if (option == JFileChooser.APPROVE_OPTION) {
                    path = chooser.getSelectedFile().getAbsolutePath();
                    Editor.lastPath = chooser.getSelectedFile().getParent();
                    copyMusic(new File(path));
                    button.setText("");
                    try {
                        button.setIcon(
                                new ImageIcon(ImageIO.read(ImageGetter.class.getResource("remove.png"))));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    gs.set("music.name", new File(path).getName());
                    try {
                        gs.save(new File("projects/" + Editor.getProjectName() + "/general.rbd"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    name.setText(new File(path).getName());
                    preview.setEnabled(true);
                }
            }
        }

    });
    if (new File("projects/" + Editor.getProjectName() + "/music.wav").exists()) {
        preview.setEnabled(true);
    } else {
        preview.setEnabled(false);
    }
    preview.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            JToggleButton tb = (JToggleButton) event.getSource();
            if (tb.isSelected()) {
                try {
                    audioStream = AudioSystem.getAudioInputStream(
                            new File("projects/" + Editor.getProjectName() + "/music.wav"));
                    format = audioStream.getFormat();
                    info = new DataLine.Info(Clip.class, format);
                    clip = (Clip) AudioSystem.getLine(info);
                    clip.open(audioStream);
                    clip.start();
                    gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
                    gainControl.setValue(dB);
                    if (loop.isSelected()) {
                        clip.loop(Clip.LOOP_CONTINUOUSLY);
                    } else {
                        clip.loop(0);
                    }
                    clip.addLineListener(new LineListener() {
                        @Override
                        public void update(LineEvent event) {
                            Clip clip = (Clip) event.getSource();
                            if (!clip.isRunning()) {
                                preview.setSelected(false);
                                clip.stop();
                                clip.close();
                                try {
                                    audioStream.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                    });
                } catch (Exception exc) {
                    exc.printStackTrace();
                }
            } else {
                clip.stop();
                clip.close();
                try {
                    audioStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    });
    JPanel buttons = new JPanel();
    buttons.setLayout(new BorderLayout());
    buttons.add(browse, BorderLayout.WEST);
    buttons.add(preview, BorderLayout.EAST);
    browsePanel.setLayout(new BorderLayout());
    browsePanel.add(buttons, BorderLayout.NORTH);
    browsePanel.add(name, BorderLayout.SOUTH);

    name.setPreferredSize(new Dimension(280, 25));
    name.setText(gs.getString("music.name"));
    content.add(browsePanel);

    this.setContentPane(content);
    this.setVisible(true);
}

From source file:Compare.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    // TODO add your handling code here:

    String userDir = System.getProperty("user.home");
    JFileChooser folder = new JFileChooser(userDir + "/Desktop");
    folder.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    folder.setFileSelectionMode(JFileChooser.FILES_ONLY);
    FileNameExtensionFilter xmlfilter = new FileNameExtensionFilter("Excel Files  (*.xls)", "xls");
    folder.setFileFilter(xmlfilter);/*www  .j a  va  2s  .com*/
    int returnvalue = folder.showSaveDialog(this);

    File myfolder = null;
    if (returnvalue == JFileChooser.APPROVE_OPTION) {
        myfolder = folder.getSelectedFile();
        //            System.out.println(myfolder);         
    }

    if (myfolder != null) {
        JOptionPane.showMessageDialog(null, "The current choosen file directory is : " + myfolder);

        listofFiles1(myfolder);
        sortByName1();
    }

    DefaultTableModel model = (DefaultTableModel) FileDetails1.getModel();

    int count = 1;

    System.out.println(filenames2.size());
    for (Files filename : filenames2) {
        String size = Long.toString(filename.Filesize) + "Bytes";
        model.addRow(new Object[] { count++, filename.Filename, size, filename.FileLocation });
    }

}