Example usage for java.awt FileDialog getFile

List of usage examples for java.awt FileDialog getFile

Introduction

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

Prototype

public String getFile() 

Source Link

Document

Gets the selected file of this file dialog.

Usage

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

/**
 * Do in background./*  w ww  .j a  v  a 2  s .  c o  m*/
 *
 * @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:org.mbs3.juniuploader.gui.pnlWoWDirectories.java

private void btnAddDirectoryActionPerformed(ActionEvent evt) {
    if (evt.getSource() == this.btnAddDirectory) {
        boolean failed = false;
        boolean mac = Util.isMac();
        if (mac) {
            java.awt.Frame f = jUniUploader.inst;
            FileDialog fd = new FileDialog(f, "Select a World of Warcraft Directory", FileDialog.LOAD);
            try {
                fd.show();/*from  w  ww. jav  a 2  s. c om*/

                String fileName = fd.getFile();
                String rootDir = fd.getDirectory();
                String completePath = (rootDir == null ? "" : rootDir) + (fileName == null ? "" : fileName);
                log.debug("Adding OS X style " + completePath);
                if (completePath != null) {
                    File file = new File(completePath);
                    if (file != null && file.exists() && file.isDirectory()) {
                        WDirectory wd = new WDirectory(file);
                        frmMain.wowDirectories.addElement(wd);
                    }

                }

            } catch (Exception ex) {
                failed = true;
                log.warn("Failed trying to display a FileDialog, falling back to JFileChooser", ex);
            }

        }
        if (!mac || failed) {
            JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int returnVal = fc.showOpenDialog(this);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                if (file != null && file.exists() && file.isDirectory()) {
                    WDirectory wd = new WDirectory(file);
                    frmMain.wowDirectories.addElement(wd);
                }

            } else {
                log.trace("Open command cancelled by user.");
            }

        }
    }
}

From source file:org.cds06.speleograph.actions.OpenAction.java

/**
 * Invoked when an action occurs.//from   w  w  w . j  av a 2 s  . c om
 */
@Override
public void actionPerformed(ActionEvent e) {
    chooser.setCurrentDirectory(SpeleoGraphApp.getWorkingDirectory());
    File file = null;
    if (SpeleoGraphApp.isMac()) {
        do {
            if (file != null && !fileFilter.accept(file)) {
                JOptionPane.showMessageDialog(SpeleoGraphApp.getInstance(),
                        I18nSupport.translate("actions.open.formaterror"), I18nSupport.translate("error"),
                        JOptionPane.ERROR_MESSAGE);
            }
            FileDialog chooserMac = new FileDialog(SpeleoGraphApp.getInstance());
            chooserMac.setDirectory(SpeleoGraphApp.getWorkingDirectory().getAbsolutePath());
            chooserMac.setVisible(true);
            if (chooserMac.getFile() == null)
                return;
            file = FileUtils.getFile(chooserMac.getDirectory(), chooserMac.getFile());
            if (file.isDirectory())
                return;
        } while (!fileFilter.accept(file));
    } else {
        int result = chooser.showOpenDialog(parent);
        switch (result) {
        case JFileChooser.APPROVE_OPTION:
            file = chooser.getSelectedFile();
            if (file.isDirectory())
                return;
            break;
        case JFileChooser.CANCEL_OPTION:
        default:
            SpeleoGraphApp.setWorkingDirectory(chooser.getCurrentDirectory());
            return;
        }
    }
    try {
        SpeleoGraphApp.setWorkingDirectory(file.getParentFile());
        reader.readFile(file);
    } catch (FileReadingError e1) {
        log.error("Error when try to read a SpeleoGraph File", e1);
    }
}

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 w  w w. j a  v a 2s  .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  w  ww  .jav a2  s  . c  om*/
    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:utybo.branchingstorytree.swing.editor.StoryEditor.java

public boolean saveAs() {
    FileDialog fd = new FileDialog(OpenBSTGUI.getInstance(), Lang.get("editor.saveloc"), FileDialog.SAVE);
    fd.setLocationRelativeTo(OpenBSTGUI.getInstance());
    fd.setVisible(true);//from ww  w .java 2s . c  o m
    if (fd.getFile() != null) {
        final File file = new File(fd.getFile().endsWith(".bst") ? fd.getDirectory() + fd.getFile()
                : fd.getDirectory() + fd.getFile() + ".bst");
        try {
            doSave(file);
            lastFileLocation = file;
            return true;
        } catch (IOException | BSTException e1) {
            OpenBST.LOG.error("Failed saving a file", e1);
            Messagers.showException(OpenBSTGUI.getInstance(), Lang.get("editor.savefail"), e1);
        }
    }
    return false;
}

From source file:FileViewer.java

/**
 * Handle button clicks//from   ww  w .j  av  a 2 s.  c o  m
 */
public void actionPerformed(ActionEvent e) {
    String cmd = e.getActionCommand();
    if (cmd.equals("open")) { // If user clicked "Open" button
        // Create a file dialog box to prompt for a new file to display
        FileDialog f = new FileDialog(this, "Open File", FileDialog.LOAD);
        f.setDirectory(directory); // Set the default directory

        // Display the dialog and wait for the user's response
        f.show();

        directory = f.getDirectory(); // Remember new default directory
        setFile(directory, f.getFile()); // Load and display selection
        f.dispose(); // Get rid of the dialog box
    } else if (cmd.equals("close")) // If user clicked "Close" button
        this.dispose(); // then close the window
}

From source file:Sampler.java

private void createUI() {
    setFont(new Font("Serif", Font.PLAIN, 12));
    setLayout(new BorderLayout());
    // Set our location to the left of the image frame.
    setSize(200, 350);//from  w  ww. j a v a 2  s  .  c  om
    Point pt = mImageFrame.getLocation();
    setLocation(pt.x - getSize().width, pt.y);

    final Checkbox accumulateCheckbox = new Checkbox("Accumulate", false);
    final Label statusLabel = new Label("");

    // Make a sorted list of the operators.
    Enumeration e = mOps.keys();
    Vector names = new Vector();
    while (e.hasMoreElements())
        names.addElement(e.nextElement());
    Collections.sort(names);
    final java.awt.List list = new java.awt.List();
    for (int i = 0; i < names.size(); i++)
        list.add((String) names.elementAt(i));
    add(list, BorderLayout.CENTER);

    // When an item is selected, do the corresponding transformation.
    list.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent ie) {
            if (ie.getStateChange() != ItemEvent.SELECTED)
                return;
            String key = list.getSelectedItem();
            BufferedImageOp op = (BufferedImageOp) mOps.get(key);
            BufferedImage source = mSplitImageComponent.getSecondImage();
            boolean accumulate = accumulateCheckbox.getState();
            if (source == null || accumulate == false)
                source = mSplitImageComponent.getImage();
            String previous = mImageFrame.getTitle() + " + ";
            if (accumulate == false)
                previous = "";
            mImageFrame.setTitle(previous + key);
            statusLabel.setText("Performing " + key + "...");
            list.setEnabled(false);
            accumulateCheckbox.setEnabled(false);
            BufferedImage destination = op.filter(source, null);
            mSplitImageComponent.setSecondImage(destination);
            mSplitImageComponent.setSize(mSplitImageComponent.getPreferredSize());
            mImageFrame.setSize(mImageFrame.getPreferredSize());
            list.setEnabled(true);
            accumulateCheckbox.setEnabled(true);
            statusLabel.setText("Performing " + key + "...done.");
        }
    });

    Button loadButton = new Button("Load...");
    loadButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            FileDialog fd = new FileDialog(Sampler.this);
            fd.show();
            if (fd.getFile() == null)
                return;
            String path = fd.getDirectory() + fd.getFile();
            mSplitImageComponent.setImage(path);
            mSplitImageComponent.setSecondImage(null);
            //            Utilities.sizeContainerToComponent(mImageFrame,
            //               mSplitImageComponent);
            mImageFrame.validate();
            mImageFrame.repaint();
        }
    });

    Panel bottom = new Panel(new GridLayout(2, 1));
    Panel topBottom = new Panel();
    topBottom.add(accumulateCheckbox);
    topBottom.add(loadButton);
    bottom.add(topBottom);
    bottom.add(statusLabel);
    add(bottom, BorderLayout.SOUTH);

    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            mImageFrame.dispose();
            dispose();
            System.exit(0);
        }
    });
}

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

/**
 * This method initializes jButton  /*from   ww  w  .  ja va2s  . c o  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: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 {// ww w  .j a  v  a 2 s . c  om
        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."));
    }
}