Example usage for java.awt FileDialog FileDialog

List of usage examples for java.awt FileDialog FileDialog

Introduction

In this page you can find the example usage for java.awt FileDialog FileDialog.

Prototype

public FileDialog(Dialog parent, String title, int mode) 

Source Link

Document

Creates a file dialog window with the specified title for loading or saving a file.

Usage

From source file:Main.java

/**
 * Select the file path via {@linkplain FileDialog}.
 * /*w w  w .  j a v a  2  s  .com*/
 * @param parent
 *            the parent of {@linkplain FileDialog}
 * @param title
 *            the title of {@linkplain FileDialog}
 * @return the selected path
 */
public static String selectPath(Frame parent, String title) {
    FileDialog dialog = new FileDialog(parent, title, FileDialog.LOAD);
    dialog.setVisible(true);
    String dir = dialog.getDirectory();
    dialog.dispose();
    return dir;
}

From source file:MainClass.java

MainClass() {
    super("MainClass");
    setSize(200, 200);/*from w w  w  .j  av  a  2s. co m*/

    fc = new FileDialog(this, "Choose a file", FileDialog.LOAD);
    fc.setDirectory("C:\\");

    Button b;
    add(b = new Button("Browse...")); // Create and add a Button
    b.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            fc.setVisible(true);
            String fn = fc.getFile();
            if (fn == null)
                System.out.println("You cancelled the choice");
            else
                System.out.println("You chose " + fn);
        }
    });
}

From source file:com.moneydance.modules.features.importlist.io.MacOSDirectoryChooser.java

@Override
void chooseBaseDirectory() {
    System.setProperty("apple.awt.fileDialogForDirectories", "true");
    final FileDialog fileDialog = new FileDialog((Frame) null, this.getLocalizable().getDirectoryChooserTitle(),
            FileDialog.LOAD);/*from  www  .  ja  v a 2 s . c o m*/
    fileDialog.setModal(true);
    fileDialog.setFilenameFilter(DirectoryValidator.INSTANCE);

    try {
        fileDialog.setDirectory(FileUtils.getUserDirectory().getAbsolutePath());
    } catch (SecurityException e) {
        LOG.log(Level.WARNING, e.getMessage(), e);
    }

    if (this.getBaseDirectory() != null) {
        final File parentDirectory = this.getBaseDirectory().getParentFile();
        if (parentDirectory != null) {
            fileDialog.setDirectory(parentDirectory.getAbsolutePath());
        }
    }
    fileDialog.setVisible(true);
    System.setProperty("apple.awt.fileDialogForDirectories", "false");

    if (fileDialog.getFile() == null) {
        return;
    }

    this.getPrefs()
            .setBaseDirectory(new File(fileDialog.getDirectory(), fileDialog.getFile()).getAbsolutePath());

    LOG.info(String.format("Base directory is %s", this.getPrefs().getBaseDirectory()));
}

From source file:uk.nhs.cfh.dsp.srth.desktop.modules.queryresultspanel.actions.ExportResultTask.java

@Override
protected Void doInBackground() throws Exception {

    // open file dialog to get save location
    FileDialog fd = new FileDialog(applicationService.getFrameView().getActiveFrame(),
            "Select location to save", FileDialog.SAVE);
    fd.setVisible(true);/*from ww w .  j  av a2 s  .c  o m*/

    String selectedFile = fd.getFile();
    String selectedDirectory = fd.getDirectory();
    if (selectedDirectory != null && selectedFile != null && resultSet != null) {
        try {
            // save to selected location
            File file = new File(selectedDirectory, selectedFile);
            // export to flat file
            FileWriter fw = new FileWriter(file);
            fw.flush();

            // add column names to data
            String cols = "";
            int colNum = resultSet.getMetaData().getColumnCount();
            for (int c = 0; c < colNum; c++) {
                cols = cols + "\t" + resultSet.getMetaData().getColumnName(c + 1);
            }

            // trim line and add new line character
            cols = cols.trim();
            cols = cols + "\n";
            // write to file
            fw.write(cols);

            float totalRows = resultSetCount;
            float percent = 0;
            int counter = 0;

            // reset resultSet to first row in case its been iterated over before
            resultSet.beforeFirst();
            while (resultSet.next()) {
                String line = "";
                for (int l = 0; l < colNum; l++) {
                    Object o = resultSet.getObject(l + 1);
                    if (o instanceof Date) {
                        o = sdf.format((Date) o);
                    } else if (o instanceof byte[]) {
                        byte[] bytes = (byte[]) o;
                        o = UUID.nameUUIDFromBytes(bytes).toString();
                    }

                    line = line + "\t" + o.toString();
                }

                // trim line
                line = line.trim();
                // append new line character to line
                line = line + "\n";
                // write to file
                fw.write(line);

                // update progress bar
                percent = (counter / totalRows) * 100;
                setProgress((int) percent);
                setMessage("Exported " + counter + " of " + totalRows + " rows");

                counter++;
            }

            // close file writer
            fw.close();

        } catch (IOException e) {
            logger.warn("Nested exception is : " + e.fillInStackTrace());
        }
    }

    return null;
}

From source file:ustc.sse.rjava.RJavaInterface.java

public String rChooseFile(Rengine re, int newFile) {
    FileDialog fd = new FileDialog(new Frame(), (newFile == 0) ? "Select a file" : "Select a new file",
            (newFile == 0) ? FileDialog.LOAD : FileDialog.SAVE);
    fd.setVisible(true);//from   www. j a v  a 2  s .  c o  m
    String res = null;
    if (fd.getDirectory() != null)
        res = fd.getDirectory();
    if (fd.getFile() != null)
        res = (res == null) ? fd.getFile() : (res + fd.getFile());
    return res;
}

From source file:uk.nhs.cfh.dsp.srth.desktop.actions.querycrud.core.actions.SaveQueryToFileTask.java

/**
 * Do in background.//from   ww w.  j  a  v a2s. c  o  m
 * 
 * @return the void
 * 
 * @throws Exception the exception
 */
@Override
protected Boolean doInBackground() throws Exception {

    boolean result = false;
    QueryStatement query = queryService.getActiveQuery();
    // open file dialog to get save location
    FileDialog fd = new FileDialog(applicationService.getFrameView().getActiveFrame(),
            "Select location to save", FileDialog.SAVE);
    fd.setVisible(true);

    String selectedFile = fd.getFile();
    String selectedDirectory = fd.getDirectory();
    fileSelected = fd.getFile();
    if (selectedDirectory != null && selectedFile != null) {
        // save to selected location
        File physicalLocation = new File(selectedDirectory, selectedFile);
        query.setPhysicalLocation(physicalLocation.toURI());
        queryExpressionFileOutputter.save(query, physicalLocation.toURI());

        // notify query has changed
        queryService.queryChanged(query, this);
        // change result to true
        result = true;
    }

    return result;
}

From source file:ec.display.chart.StatisticsChartPaneTab.java

/**
 * This method initializes jButton  /*from w w  w.  ja  v a 2  s .co  m*/
 *  
 * @return javax.swing.JButton      
 */
private JButton getPrintButton() {
    if (printButton == null) {
        printButton = new JButton();
        printButton.setText("Export to PDF...");
        final JFreeChart chart = chartPane.getChart();
        printButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                try

                {
                    int width = chartPane.getWidth();
                    int height = chartPane.getHeight();

                    FileDialog fileDialog = new FileDialog(new Frame(), "Export...", FileDialog.SAVE);
                    fileDialog.setDirectory(System.getProperty("user.dir"));
                    fileDialog.setFile("*.pdf");
                    fileDialog.setVisible(true);
                    String fileName = fileDialog.getFile();
                    if (fileName != null)

                    {
                        if (!fileName.endsWith(".pdf")) {
                            fileName = fileName + ".pdf";
                        }
                        File f = new File(fileDialog.getDirectory(), fileName);
                        Document document = new Document(new com.lowagie.text.Rectangle(width, height));
                        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(f));
                        document.addAuthor("ECJ Console");
                        document.open();
                        PdfContentByte cb = writer.getDirectContent();
                        PdfTemplate tp = cb.createTemplate(width, height);
                        Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
                        Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, width, height);
                        chart.draw(g2, rectangle2D);
                        g2.dispose();
                        cb.addTemplate(tp, 0, 0);
                        document.close();
                    }
                } catch (Exception ex)

                {
                    ex.printStackTrace();
                }
            }
        });
    }
    return printButton;
}

From source file:GUIMediaStatistics.java

/************************************************************************
* Respond to user button presses - either browsing for a file or
* gathering format info on the current file.
************************************************************************/
public void actionPerformed(ActionEvent e) {

    /////////////////////////////////
    // Browse - use FileDialog class.
    /////////////////////////////////
    if (e.getSource() == browseButton) {
        FileDialog choice = new FileDialog(this, "Media File Choice", FileDialog.LOAD);
        if (lastDirectory != null)
            choice.setDirectory(lastDirectory);
        choice.show();/*from  w ww  .j ava 2  s .  c  o m*/
        String selection = choice.getFile();
        if (selection != null) {
            lastDirectory = choice.getDirectory();
            mediaField.setText("file://" + choice.getDirectory() + selection);
        }
    }
    ////////////////////////////////////////////////////////
    // Get statistics - create a MediaStatistics object and
    // monitor its progress.
    ///////////////////////////////////////////////////////
    else {
        stats = new MediaStatistics(mediaField.getText());
        monitorAndReport();
    }
}

From source file:uk.nhs.cfh.dsp.srth.desktop.actions.querycrud.core.actions.LoadSavedQueryTask.java

/**
 * Do in background./*from  ww  w  .j  a  v a  2s.  c  om*/
 *
 * @return the query statement
 *
 * @throws Exception the exception
 */
@Override
protected Void doInBackground() throws Exception {

    // open file dialog
    FileDialog fd = new FileDialog(applicationService.getFrameView().getActiveFrame(), "Select file to load",
            FileDialog.LOAD);
    fd.setVisible(true);

    fileSelected = fd.getFile();
    String directorySelected = fd.getDirectory();
    if (fileSelected != null && directorySelected != null) {
        File physicalFile = new File(directorySelected, fileSelected);
        // use file name load file from
        XMLLoader loader = new XMLLoader();
        Document doc = loader.getXMLDoc(physicalFile);

        query = queryExpressionXMLConverter.getQueryStatementFromElement(doc.getRootElement());
        if (query != null) {
            // assign physical location to query
            query.setPhysicalLocation(physicalFile.toURI());

            // register query and set to active query
            queryService.registerQuery(query);
            queryService.queryChanged(query, this);
        }
    }

    return null;
}

From source file:processing.app.tools.Archiver.java

public void run() {
    SketchController sketch = editor.getSketchController();

    // first save the sketch so that things don't archive strangely
    boolean success = false;
    try {//from w w  w.j a v  a  2s  .  c  o m
        success = sketch.save();
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (!success) {
        Base.showWarning(tr("Couldn't archive sketch"),
                tr("Archiving the sketch has been canceled because\nthe sketch couldn't save properly."), null);
        return;
    }

    File location = sketch.getSketch().getFolder();
    String name = location.getName();
    File parent = new File(location.getParent());

    //System.out.println("loc " + location);
    //System.out.println("par " + parent);

    File newbie = null;
    String namely = null;
    int index = 0;
    do {
        // only use the date if the sketch name isn't the default name
        useDate = !name.startsWith("sketch_");

        if (useDate) {
            String purty = dateFormat.format(new Date());
            String stamp = purty + ((char) ('a' + index));
            namely = name + "-" + stamp;
            newbie = new File(parent, namely + ".zip");

        } else {
            String diggie = numberFormat.format(index + 1);
            namely = name + "-" + diggie;
            newbie = new File(parent, namely + ".zip");
        }
        index++;
    } while (newbie.exists());

    // open up a prompt for where to save this fella
    FileDialog fd = new FileDialog(editor, tr("Archive sketch as:"), FileDialog.SAVE);
    fd.setDirectory(parent.getAbsolutePath());
    fd.setFile(newbie.getName());
    fd.setVisible(true);

    String directory = fd.getDirectory();
    String filename = fd.getFile();

    // only write the file if not canceled
    if (filename != null) {
        newbie = new File(directory, filename);

        ZipOutputStream zos = null;
        try {
            //System.out.println(newbie);
            zos = new ZipOutputStream(new FileOutputStream(newbie));

            // recursively fill the zip file
            buildZip(location, name, zos);

            // close up the jar file
            zos.flush();
            editor.statusNotice("Created archive " + newbie.getName() + ".");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(zos);
        }
    } else {
        editor.statusNotice(tr("Archive sketch canceled."));
    }
}