Example usage for java.awt FileDialog setDirectory

List of usage examples for java.awt FileDialog setDirectory

Introduction

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

Prototype

public void setDirectory(String dir) 

Source Link

Document

Sets the directory of this file dialog window to be the specified directory.

Usage

From source file:Main.java

/**
 * @param jFrame//from   ww  w.  jav  a2  s.  c om
 * @param currentDirectory
 * @return You can get the filename with fileDialog.getFile(),
 * and you can get the directory with fileDialog.getDirectory().
 * String filename = fileDialog.getDirectory() + System.getProperty("file.separator") + fileDialog.getFile();
 * 
 */
public static FileDialog letUserChooseFile(JFrame jFrame, String currentDirectory) {
    FileDialog fileDialog = new FileDialog(jFrame);
    fileDialog.setModal(true);
    fileDialog.setMode(FileDialog.LOAD);
    fileDialog.setTitle("Open a File");
    if (currentDirectory != null && !currentDirectory.trim().equals("")) {
        fileDialog.setDirectory(currentDirectory);
    }
    fileDialog.setVisible(true);
    return fileDialog;
}

From source file:edu.ku.brc.specify.tasks.services.PickListUtils.java

/**
 * @param localizableIO//from w ww. ja  v  a2  s.c  o m
 * @param collection
 * @return
 */
public static boolean importPickLists(final LocalizableIOIFace localizableIO, final Collection collection) {
    // Apply is Import All PickLists

    FileDialog dlg = new FileDialog(((Frame) UIRegistry.getTopWindow()),
            getResourceString(getI18n("PL_IMPORT")), FileDialog.LOAD);
    dlg.setDirectory(UIRegistry.getUserHomeDir());
    dlg.setFile(getPickListXMLName());
    UIHelper.centerAndShow(dlg);

    String dirStr = dlg.getDirectory();
    String fileName = dlg.getFile();
    if (StringUtils.isEmpty(dirStr) || StringUtils.isEmpty(fileName)) {
        return false;
    }

    final String path = dirStr + fileName;

    File file = new File(path);
    if (!file.exists()) {
        UIRegistry.showLocalizedError(getI18n("PL_FILE_NOT_EXIST"), file.getAbsoluteFile());
        return false;
    }
    List<BldrPickList> bldrPickLists = DataBuilder.getBldrPickLists(null, file);

    Integer cnt = null;
    boolean wasErr = false;

    DataProviderSessionIFace session = null;
    try {
        session = DataProviderFactory.getInstance().createSession();
        session.beginTransaction();

        HashMap<String, PickList> plHash = new HashMap<String, PickList>();
        List<PickList> items = getPickLists(localizableIO, true, false);

        for (PickList pl : items) {
            plHash.put(pl.getName(), pl);
            //System.out.println("["+pl.getName()+"]");
        }

        for (BldrPickList bpl : bldrPickLists) {
            PickList pickList = plHash.get(bpl.getName());
            //System.out.println("["+bpl.getName()+"]["+(pickList != null ? pickList.getName() : "null") + "]");
            if (pickList == null) {
                // External PickList is new
                pickList = createPickList(bpl, collection);
                session.saveOrUpdate(pickList);
                if (cnt == null)
                    cnt = 0;
                cnt++;

            } else if (!pickListsEqual(pickList, bpl)) {
                session.delete(pickList);
                collection.getPickLists().remove(pickList);
                pickList = createPickList(bpl, collection);
                session.saveOrUpdate(pickList);
                collection.getPickLists().add(pickList);
                if (cnt == null)
                    cnt = 0;
                cnt++;
            }
        }
        session.commit();

    } catch (Exception ex) {
        wasErr = true;
        if (session != null)
            session.rollback();

        ex.printStackTrace();
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(PickListEditorDlg.class, ex);

    } finally {
        if (session != null) {
            session.close();
        }
    }

    String key = wasErr ? "PL_ERR_IMP" : cnt != null ? "PL_WASIMPORT" : "PL_MATCHIMP";

    UIRegistry.displayInfoMsgDlgLocalized(getI18n(key), cnt);

    return true;
}

From source file:edu.ku.brc.specify.tasks.services.PickListUtils.java

/**
 * @param localizableIO//from ww  w .j  a  va 2s.  c  om
 * @param hash HashSet of names of picklists to be pre-selected (can be null)
 */
public static void exportPickList(final LocalizableIOIFace localizableIO, final HashSet<String> hash) {
    // Cancel is Export All PickLists

    List<PickList> items = getPickLists(localizableIO, true, false);
    List<PickList> selectedItems = new ArrayList<PickList>();
    if (hash != null) {
        for (PickList pl : items) {
            if (hash.contains(pl.getName())) {
                selectedItems.add(pl);
            }
        }
    }

    Window window = UIRegistry.getTopWindow();
    boolean isDialog = window instanceof Dialog;

    ToggleButtonChooserDlg<PickList> pickDlg;
    if (isDialog) {
        pickDlg = new ToggleButtonChooserDlg<PickList>((Dialog) window, getI18n("PL_EXPORT"), items);
    } else {
        pickDlg = new ToggleButtonChooserDlg<PickList>((JFrame) window, getI18n("PL_EXPORT"), items);
    }

    pickDlg.setUseScrollPane(true);
    pickDlg.setAddSelectAll(true);
    pickDlg.createUI();
    pickDlg.setSelectedObjects(selectedItems);
    UIHelper.centerAndShow(pickDlg);

    Integer cnt = null;
    if (!pickDlg.isCancelled()) {
        items = pickDlg.getSelectedObjects();

        String dlgTitle = getResourceString(getI18n("RIE_ExportResource"));

        FileDialog dlg;
        if (isDialog) {
            dlg = new FileDialog((Dialog) window, dlgTitle, FileDialog.SAVE);
        } else {
            dlg = new FileDialog((Frame) window, dlgTitle, FileDialog.SAVE);
        }
        dlg.setDirectory(UIRegistry.getUserHomeDir());
        dlg.setFile(getPickListXMLName());

        UIHelper.centerAndShow(dlg);

        String dirStr = dlg.getDirectory();
        String fileName = dlg.getFile();

        if (StringUtils.isNotEmpty(dirStr) && StringUtils.isNotEmpty(fileName)) {
            String ext = FilenameUtils.getExtension(fileName);
            if (StringUtils.isEmpty(ext) || !ext.equalsIgnoreCase("xml")) {
                fileName += ".xml";
            }

            try {
                File xmlFile = new File(dirStr + File.separator + fileName);

                ArrayList<BldrPickList> bldrPickLists = new ArrayList<BldrPickList>();
                for (PickList pl : items) {
                    bldrPickLists.add(new BldrPickList(pl));
                }
                DataBuilder.writePickListsAsXML(xmlFile, bldrPickLists);
                cnt = bldrPickLists.size();

            } catch (Exception ex) {
                ex.printStackTrace();
            }
            UIRegistry.displayInfoMsgDlgLocalized(getI18n(cnt != null ? "PL_WASEXPORT" : "PL_ERR_IMP"), cnt);
        }
    }
}

From source file:FileViewer.java

/**
 * Handle button clicks// w  w  w .  ja va 2  s .  c  om
 */
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: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  .  jav a 2 s. co 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:ec.display.chart.StatisticsChartPaneTab.java

/**
 * This method initializes jButton  /*  w w  w.ja v  a  2s .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: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);// w  w w  .j av  a  2 s. co  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:Forms.CreateGearForm.java

private GearSpec loadGearSpec() {
    //Get top level frame
    JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(MasterPanel);

    //Create dialog for choosing gearspec file
    FileDialog fd = new FileDialog(topFrame, "Choose a .gearspec file", FileDialog.LOAD);
    fd.setDirectory(System.getProperty("user.home"));
    fd.setFile("*.gearspec");
    fd.setVisible(true);//  ww  w. j av a2s .  com
    //Get file
    String filename = fd.getFile();
    if (filename == null)
        System.out.println("You cancelled the choice");
    else {
        System.out.println("You chose " + filename);

        //Get spec file
        File specFile = new File(fd.getDirectory() + Utils.pathSeparator() + filename);

        //If it exists, set it as the selected file path
        if (specFile.exists()) {
            //Generate spec
            return Utils.specForFile(specFile);
        }
    }

    return null;
}

From source file:Forms.CreateGearForm.java

private Boolean saveSpec(GearSpec spec) {

    //Get top level frame
    JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(MasterPanel);

    //Create dialog for choosing gearspec file
    FileDialog fd = new FileDialog(topFrame, "Save .gearspec file", FileDialog.SAVE);
    fd.setDirectory(System.getProperty("user.home"));
    // Gets the name that is specified for the spec in the beginning
    fd.setFile(spec.getName() + ".gearspec");
    fd.setVisible(true);//from ww w. j  a v a2 s.c om
    //Get file
    String filename = fd.getFile();
    if (filename == null) {
        System.out.println("You cancelled the choice");
        return false;
    } else {
        System.out.println("You chose " + filename);

        //Get spec file
        File specFile = new File(fd.getDirectory() + Utils.pathSeparator() + filename);

        //Serialize spec to string
        String gearString = gson.toJson(spec);

        try {
            //If it exists, set it as the selected file path
            if (specFile.exists()) {
                FileUtils.forceDelete(specFile);
            }

            //Write new spec
            FileUtils.write(specFile, gearString);
        } catch (IOException e) {
            e.printStackTrace();
            showSaveErrorDialog();
            return false;
        }

        return true;
    }
}

From source file:PlayerOfMedia.java

/***************************************************************************
 * React to menu selections (quit or open) or one of the the buttons on the
 * dialog boxes./*from   ww w . java 2  s .co  m*/
 **************************************************************************/
public void actionPerformed(ActionEvent e) {

    if (e.getSource() instanceof MenuItem) {
        //////////////////////////////////////////////////
        // Quit and free up any player acquired resources.
        //////////////////////////////////////////////////
        if (e.getActionCommand().equalsIgnoreCase("QUIT")) {
            if (player != null) {
                player.stop();
                player.close();
            }
            System.exit(0);
        }
        /////////////////////////////////////////////////////////
        // User to open/play media. Show the selection dialog box.
        /////////////////////////////////////////////////////////
        else if (e.getActionCommand().equalsIgnoreCase("OPEN")) {
            selectionDialog.show();
        }
    }
    //////////////////////
    // One of the Buttons.
    //////////////////////
    else {
        /////////////////////////////////////////////////////////////
        // User to browse the local file system. Popup a file dialog.
        /////////////////////////////////////////////////////////////
        if (e.getSource() == choose) {
            FileDialog choice = new FileDialog(this, "Media File Choice", FileDialog.LOAD);
            if (lastDirectory != null)
                choice.setDirectory(lastDirectory);
            choice.show();
            String selection = choice.getFile();
            if (selection != null) {
                lastDirectory = choice.getDirectory();
                mediaName.setText("file://" + choice.getDirectory() + selection);
            }
        }
        ///////////////////////////////////////////////
        // User chooses to cancel opening of new media.
        ///////////////////////////////////////////////
        else if (e.getSource() == cancel) {
            selectionDialog.hide();
        }
        ///////////////////////////////////////////////////////
        // User has selected the name of the media. Attempt to
        // create a Player.
        ///////////////////////////////////////////////////////
        else if (e.getSource() == open) {
            selectionDialog.hide();
            createAPlayer(mediaName.getText());
        }
        ////////////////////////////////////////////
        // User has seen error message. Now hide it.
        ////////////////////////////////////////////
        else if (e.getSource() == ok)
            errorDialog.hide();
    }
}