Example usage for javax.swing JFileChooser getSelectedFile

List of usage examples for javax.swing JFileChooser getSelectedFile

Introduction

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

Prototype

public File getSelectedFile() 

Source Link

Document

Returns the selected file.

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.//from w  w w .ja  va 2  s.c  om
 *
 * @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:com.holycityaudio.SpinCAD.SpinCADFile.java

public void fileSaveAsm(SpinCADPatch patch) {
    // Create a file chooser
    String savedPath = prefs.get("MRUSpnFolder", "");

    final JFileChooser fc = new JFileChooser(savedPath);
    // In response to a button click:
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Spin ASM Files", "spn");
    fc.setFileFilter(filter);/*from   w w  w .ja  v  a2s  .  co m*/
    // XXX DEBUG
    fc.showSaveDialog(new JFrame());
    File fileToBeSaved = fc.getSelectedFile();

    if (!fc.getSelectedFile().getAbsolutePath().endsWith(".spn")) {
        fileToBeSaved = new File(fc.getSelectedFile() + ".spn");
    }
    int n = JOptionPane.YES_OPTION;
    if (fileToBeSaved.exists()) {
        JFrame frame1 = new JFrame();
        n = JOptionPane.showConfirmDialog(frame1, "Would you like to overwrite it?", "File already exists!",
                JOptionPane.YES_NO_OPTION);
    }
    if (n == JOptionPane.YES_OPTION) {
        String filePath = fileToBeSaved.getPath();
        fileToBeSaved.delete();

        try {
            fileSaveAsm(patch, filePath);
        } catch (IOException e) {
            JOptionPane.showOptionDialog(null, "File save error!", "Error", JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE, null, null, null);
            e.printStackTrace();
        }
        saveMRUSpnFolder(filePath);
    }
}

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

@Override
public void actionPerformed(ActionEvent ev) {
    /*//from   w  ww  .j av a  2s.  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:de.quadrillenschule.azocamsyncd.astromode.gui.AstroModeJPanel.java

private void chooseDirjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chooseDirjButtonActionPerformed
    JFileChooser jfc = new JFileChooser(astroFolderjTextField.getText());
    jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    if (jfc.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        astroFolderjTextField.setText(jfc.getSelectedFile().getAbsolutePath());
    }/*  w ww.  j  av a  2 s .  co  m*/
}

From source file:DOMTreeTest.java

/**
     * Open a file and load the document.
     *//*  www.ja  v a 2s . 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:be.vds.jtbdive.client.view.core.dive.profile.DiveProfileGraphicDetailPanel.java

private Component createExportButton() {
    exportButton = new JButton(new AbstractAction(null, UIAgent.getInstance().getIcon(UIAgent.ICON_EXPORT_24)) {

        private static final long serialVersionUID = 9021437098555924654L;

        @Override/*  w ww.ja  v  a2  s.  c  om*/
        public void actionPerformed(ActionEvent e) {
            JFileChooser ch = new JFileChooser();
            ch.setFileFilter(new ExtensionFilter("xls", "Excel File"));
            int i = ch.showSaveDialog(null);
            if (i == JFileChooser.APPROVE_OPTION) {
                DiveProfileExcelParser p = new DiveProfileExcelParser();
                try {
                    File f = ch.getSelectedFile();
                    if (FileUtilities.getExtension(f) == null
                            || !("xls".equals(FileUtilities.getExtension(f)))) {
                        f = new File(f.getAbsoluteFile() + ".xls");
                    }
                    p.export(currentDive.getDate(), diveProfile, f);
                } catch (IOException e1) {
                    ExceptionDialog.showDialog(e1, DiveProfileGraphicDetailPanel.this);
                    LOGGER.error(e1.getMessage());
                }
            }

        }
    });
    exportButton.setToolTipText("Export");
    return exportButton;
}

From source file:be.vds.jtbdive.client.view.core.dive.profile.DiveProfileGraphicDetailPanel.java

private Component createImportButton() {
    JButton b = new JButton(new AbstractAction(null, UIAgent.getInstance().getIcon(UIAgent.ICON_IMPORT_24)) {

        private static final long serialVersionUID = 985413615438877711L;

        @Override//w ww.j  a v  a2 s .  c  o m
        public void actionPerformed(ActionEvent e) {
            JFileChooser ch = new JFileChooser();
            ch.setFileFilter(new ExtensionFilter("xls", "Excel File"));
            int i = ch.showOpenDialog(null);
            if (i == JFileChooser.APPROVE_OPTION) {
                DiveProfileExcelParser p = new DiveProfileExcelParser();
                try {
                    File f = ch.getSelectedFile();
                    DiveProfile dp = p.read(f);
                    I18nResourceManager i18n = I18nResourceManager.sharedInstance();
                    int yes = JOptionPane.showConfirmDialog(DiveProfileGraphicDetailPanel.this,
                            i18n.getString("overwritte.diveprofile.confirm"), i18n.getString("confirmation"),
                            JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
                    if (yes == JOptionPane.YES_OPTION) {
                        currentDive.setDiveProfile(dp);
                        setDiveProfile(dp, currentDive);
                        logBookManagerFacade.setDiveChanged(currentDive);
                    }
                } catch (IOException e1) {
                    ExceptionDialog.showDialog(e1, DiveProfileGraphicDetailPanel.this);
                    LOGGER.error(e1.getMessage());
                }
            }

        }
    });
    b.setToolTipText("Import");
    return b;
}

From source file:analysis.postRun.PostRunWindow.java

/**
 * Method which opens a file chooser so the user can select a log to view.
 *///  ww w .j  a  va2  s . c om
//   void chooseFile()
//   {
//      JFileChooser fc = new JFileChooser();
//      fc.setDialogTitle("Select Log");
//      fc.setCurrentDirectory(new File(System.getProperty("user.dir") + "/log"));
//      fc.setAcceptAllFileFilterUsed(false);
//      FileFilter filter = new FileNameExtensionFilter(" file", "csv");
//      fc.addChoosableFileFilter(filter);
//      int rVal = fc.showOpenDialog(null);
//
//      if (rVal == JFileChooser.APPROVE_OPTION)
//      {
//         currFile = fc.getSelectedFile().getAbsolutePath();
//         //System.out.println(currFile);
//         parent=fc.getSelectedFile().getParent();
//         System.out.println(parent);
//         getData(fc.getSelectedFile().getAbsolutePath());
//      }
//      else {
//         System.exit(0);
//      }
//   }

//dialogTitle="select log"
//directoryPath="/log"
//allFileFilterUsed=false
//description= "file"
//FileNameExtensionFilter
//extension = "csv"
//FileFilter filter = new FileNameExtensionFilter(" file", "csv");
void chooseFile1() {
    JFileChooser fc = GUIFileReader.getFileChooser("Select Log", "/log",
            new FileNameExtensionFilter(" file", "csv"));

    int rVal = fc.showOpenDialog(null);

    if (rVal == JFileChooser.APPROVE_OPTION) {
        currFile = fc.getSelectedFile().getAbsolutePath();
        //System.out.println(currFile);
        parent = fc.getSelectedFile().getParent();
        System.out.println(parent);
        getData(fc.getSelectedFile().getAbsolutePath());
    } else {
        System.exit(0);
    }
}

From source file:bio.gcat.gui.BDATool.java

public boolean saveFileAs() {
    JFileChooser chooser = new FileNameExtensionFileChooser(false, BDA_EXTENSION_FILTER);
    chooser.setDialogTitle("Save As");
    if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
        return saveFile(chooser.getSelectedFile());
    else/*from www .ja  va 2  s. c o m*/
        return false;
}

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

protected void exportOverview() {
    File currentDir = new File(System.getProperty("user.dir"));
    JFileChooser saveDialog = new JFileChooser(currentDir);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG File", "png", "ong");
    saveDialog.setFileFilter(filter);/*from www .j a  v a  2 s  .c  om*/
    int response = saveDialog.showSaveDialog(this);
    if (response == saveDialog.APPROVE_OPTION) {
        File outputfile = saveDialog.getSelectedFile();
        if (outputfile.getName().lastIndexOf(".") == -1) {
            outputfile = new File(outputfile.getName() + ".png");
        }
        try {
            //ImageIO.write(this.overview, "jpg", outputfile);
            BufferedImage bi = new BufferedImage(this.jLabelOverview.getIcon().getIconWidth(),
                    this.jLabelOverview.getIcon().getIconHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics g = bi.createGraphics();
            // paint the Icon to the BufferedImage.
            this.jLabelOverview.getIcon().paintIcon(null, g, 0, 0);
            g.dispose();
            ImageIO.write(bi, "png", outputfile);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}