Example usage for javax.swing JFileChooser setCurrentDirectory

List of usage examples for javax.swing JFileChooser setCurrentDirectory

Introduction

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

Prototype

@BeanProperty(preferred = true, description = "The directory that the JFileChooser is showing files of.")
public void setCurrentDirectory(File dir) 

Source Link

Document

Sets the current directory.

Usage

From source file:edu.harvard.mcz.imagecapture.jobs.JobRepeatOCR.java

private List<File> getFileList() {
    String pathToCheck = "";
    if (scan != SCAN_ALL) {
        // Find the path in which to include files.
        File imagebase = null; // place to start the scan from, imagebase directory for SCAN_ALL
        File startPoint = null;/*  w w w  . j  a v  a2  s.  c  o m*/
        // If it isn't null, retrieve the image base directory from properties, and test for read access.
        if (Singleton.getSingletonInstance().getProperties().getProperties()
                .getProperty(ImageCaptureProperties.KEY_IMAGEBASE) == null) {
            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                    "Can't start scan.  Don't know where images are stored.  Set imagbase property.",
                    "Can't Scan.", JOptionPane.ERROR_MESSAGE);
        } else {
            imagebase = new File(Singleton.getSingletonInstance().getProperties().getProperties()
                    .getProperty(ImageCaptureProperties.KEY_IMAGEBASE));
            if (imagebase != null) {
                if (imagebase.canRead()) {
                    startPoint = imagebase;
                } else {
                    // If it can't be read, null out imagebase
                    imagebase = null;
                }
            }
            if (scan == SCAN_SPECIFIC && startPointSpecific != null && startPointSpecific.canRead()) {
                // A scan start point has been provided, don't launch a dialog.
                startPoint = startPointSpecific;
            }
            if (imagebase == null || scan == SCAN_SELECT) {
                // launch a file chooser dialog to select the directory to scan
                final JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                if (scan == SCAN_SELECT && startPointSpecific != null && startPointSpecific.canRead()) {
                    fileChooser.setCurrentDirectory(startPointSpecific);
                } else {
                    if (Singleton.getSingletonInstance().getProperties().getProperties()
                            .getProperty(ImageCaptureProperties.KEY_LASTPATH) != null) {
                        fileChooser
                                .setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties()
                                        .getProperties().getProperty(ImageCaptureProperties.KEY_LASTPATH)));
                    }
                }
                int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame());
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                    log.debug("Selected base directory: " + file.getName() + ".");
                    startPoint = file;
                } else {
                    //TODO: handle error condition
                    log.error("Directory selection cancelled by user.");
                }
                //TODO: Filechooser to pick path, then save (if SCAN_ALL) imagebase property. 
                //Perhaps.  Might be undesirable behavior.
                //Probably better to warn that imagebase is null;
            }

            // Check that startPoint is or is within imagebase.
            if (!ImageCaptureProperties.isInPathBelowBase(startPoint)) {
                String base = Singleton.getSingletonInstance().getProperties().getProperties()
                        .getProperty(ImageCaptureProperties.KEY_IMAGEBASE);
                log.error("Tried to scan directory (" + startPoint.getPath()
                        + ") outside of base image directory (" + base + ")");
                String message = "Can't scan and database files outside of base image directory (" + base + ")";
                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), message,
                        "Can't Scan outside image base directory.", JOptionPane.YES_NO_OPTION);
            } else {

                // run in separate thread and allow cancellation and status reporting

                // walk through directory tree

                if (!startPoint.canRead()) {
                    JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                            "Can't start scan.  Unable to read selected directory: " + startPoint.getPath(),
                            "Can't Scan.", JOptionPane.YES_NO_OPTION);
                } else {
                    pathToCheck = ImageCaptureProperties.getPathBelowBase(startPoint);
                }
            }
        }
    }

    // Retrieve a list of all specimens in state OCR
    SpecimenLifeCycle sls = new SpecimenLifeCycle();
    Specimen pattern = new Specimen();
    pattern.setWorkFlowStatus(WorkFlowStatus.STAGE_0);
    List<Specimen> specimens = sls.findByExample(pattern);
    ArrayList<File> files = new ArrayList<File>();
    for (int i = 0; i < specimens.size(); i++) {
        Specimen s = specimens.get(i);
        Set<ICImage> images = s.getICImages();
        Iterator<ICImage> iter = images.iterator();
        while (iter.hasNext() && runStatus != RunStatus.STATUS_TERMINATED) {
            ICImage image = (ICImage) iter.next();
            if (scan == SCAN_ALL || image.getPath().startsWith(pathToCheck)) {
                // Add image for specimen to list to check
                File imageFile = new File(
                        ImageCaptureProperties.assemblePathWithBase(image.getPath(), image.getFilename()));
                files.add(imageFile);
                counter.incrementFilesSeen();
            }
        }
    }
    String message = "Found " + files.size() + " Specimen records on which to repeat OCR.";
    log.debug(message);
    Singleton.getSingletonInstance().getMainFrame().setStatusMessage(message);

    return files;
}

From source file:au.org.ala.delta.editor.DeltaEditor.java

public File selectFile(boolean open) {
    File selectedFile = null;//  w  w w .  j  a  v  a  2s. c  o m
    JFileChooser chooser = new JFileChooser();

    if (_lastDirectory != null) {
        chooser.setCurrentDirectory(_lastDirectory);
    }

    chooser.setFileFilter(new FileNameExtensionFilter("Delta Editor files *.dlt", DELTA_FILE_EXTENSION));
    int dialogResult;
    if (open) {
        dialogResult = chooser.showOpenDialog(getMainFrame());
    } else {
        dialogResult = chooser.showSaveDialog(getMainFrame());
    }
    if (dialogResult == JFileChooser.APPROVE_OPTION) {
        selectedFile = chooser.getSelectedFile();
        _lastDirectory = chooser.getCurrentDirectory();
    }
    return selectedFile;
}

From source file:com.gnadenheimer.mg.frames.admin.FrameConfigAdmin.java

private void cmdDatadirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdDatadirActionPerformed
    try {/*from www. j a  va2  s  .c  o  m*/
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle("Eligir ubicacin de la base de datos.");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);

        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            txtDatadir.setText(chooser.getSelectedFile().getPath());
        }
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null,
                Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + ex.getMessage());
        LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex);
    }
}

From source file:gui.MainGUI.java

private void menuEnvironmentMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuEnvironmentMouseClicked
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir") + "/environments/"));
    int returnVal = fileChooser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        simConfig.loadWallConfig(file.getPath());
        updateFromEnvConfig();/*from w  w  w  . java 2  s . c  om*/
    }
}

From source file:gui.MainGUI.java

private void menuEnvironmentMenuDragMouseReleased(javax.swing.event.MenuDragMouseEvent evt) {//GEN-FIRST:event_menuEnvironmentMenuDragMouseReleased
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir") + "/environments/"));
    int returnVal = fileChooser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        simConfig.loadWallConfig(file.getPath());
        updateFromEnvConfig();/*from w w  w.j a va 2s.c  om*/
    }
}

From source file:com.wet.wired.jsr.player.JPlayer.java

public void actionPerformed(ActionEvent ev) {

    if (ev.getActionCommand().equals("open")) {
        UIManager.put("FileChooser.readOnly", true);
        JFileChooser fileChooser = new JFileChooser();
        FileExtensionFilter filter = new FileExtensionFilter();

        filter = new FileExtensionFilter();
        filter.addExtension("owl");
        filter.setDescription("TestingOwl File");

        if (target != null) {
            fileChooser.setSelectedFile(new File(target + ".owl"));
        }/*from   w  ww .j a  v  a 2  s .c  o m*/
        fileChooser.setFileFilter(filter);
        fileChooser.setCurrentDirectory(new File("."));
        fileChooser.showOpenDialog(this);

        if (fileChooser.getSelectedFile() != null) {
            // target = fileChooser.getSelectedFile().getAbsolutePath();
            String targetCapOwl = fileChooser.getSelectedFile().getAbsolutePath();
            target = targetCapOwl.substring(0, targetCapOwl.lastIndexOf(".owl"));
            open();
        }
    } else if (ev.getActionCommand().equals("play")) {
        play();
    } else if (ev.getActionCommand().equals("reset")) {
        reset();
    } else if (ev.getActionCommand().equals("fastForward")) {
        fastForward();
    } else if (ev.getActionCommand().equals("pause")) {
        pause();
    } else if (ev.getActionCommand().equals("close")) {
        close();
    } else if (ev.getActionCommand().equals("recorder")) {
        closePlayer();
        Main.getRecorder().init(new String[0]);
    }
}

From source file:net.liuxuan.device.VACVBS.JIF_DrawChart_vacvbs.java

protected JFileChooser initFileChooser() {
    ExtensionFileFilter filter = new ExtensionFileFilter("log,txt", true, true);
    filter.setDescription("?");
    JFileChooser jfc = new JFileChooser();
    FileSystemView fsv = FileSystemView.getFileSystemView();
    //?/*from w ww  .  j a va 2 s.co m*/
    jfc.setCurrentDirectory(fsv.getHomeDirectory());
    jfc.setDialogTitle("?");
    jfc.setMultiSelectionEnabled(false);
    jfc.setDialogType(JFileChooser.OPEN_DIALOG);
    jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);//JFileChooser.FILES_AND_DIRECTORIES
    jfc.setFileFilter(filter);
    return jfc;
}

From source file:com.claim.ui.UiReportType5.java

private void jButtonFolder3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFolder3ActionPerformed
    try {//ww  w  .  ja  va 2 s.co m
        JFileChooser fc = new JFileChooser();
        fc.setDialogTitle("Open Folder");
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.setCurrentDirectory(new File(""));
        int result = fc.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File a = fc.getSelectedFile();
            // Path File method in this class
            String temp = a.getPath();
            txtPathFileType5.setText(".");

            if (temp != null) {
                txtPathFileType5.setText(temp);
                //txtPathFileOpaeIndv.setEnabled(true);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ca.osmcanada.osvuploadr.JPMain.java

private void jbAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAddActionPerformed
    try {//from   w  ww .  ja  v  a 2  s.c  o  m
        JFileChooser fc = new JFileChooser();
        if (!last_dir.isEmpty()) {
            fc.setCurrentDirectory(new java.io.File(last_dir)); // start at application current directory
        }
        fc.setMultiSelectionEnabled(true);
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showSaveDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            if (fc.getSelectedFiles().length == 1) {
                int response = JOptionPane.showConfirmDialog(null,
                        new String(r.getString("immediate_sub_folders").getBytes(), "UTF-8"),
                        new String(r.getString("add_subfolders").getBytes(), "UTF-8"),
                        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (response == JOptionPane.NO_OPTION) {
                    File folder = fc.getSelectedFile();
                    listDir.add(folder.getPath());
                    last_dir = folder.getPath();
                } else if (response == JOptionPane.YES_OPTION) {
                    //Get a list of subdirectories
                    String[] subDirs = fc.getSelectedFile().list(new FilenameFilter() {
                        @Override
                        public boolean accept(File current, String name) {
                            return new File(current, name).isDirectory();
                        }
                    });

                    for (String subDir : subDirs) {
                        listDir.add(new File(fc.getSelectedFile() + "/" + subDir).getPath());
                    }
                }
            } else if (fc.getSelectedFiles().length > 1) {
                File[] folders = fc.getSelectedFiles();
                for (File folder : folders) {
                    listDir.add(folder.getPath());
                    last_dir = folder.getPath();
                }
            }

        }
    } catch (UnsupportedEncodingException ex) {
    }
}

From source file:gdt.jgui.entity.folder.JFolderPanel.java

/**
 * Get the context menu.//from   w  w  w.  ja va 2  s.co m
 * @return the context menu.
 */
@Override
public JMenu getContextMenu() {
    menu = super.getContextMenu();
    mia = null;
    int cnt = menu.getItemCount();
    if (cnt > 0) {
        mia = new JMenuItem[cnt];
        for (int i = 0; i < cnt; i++)
            mia[i] = menu.getItem(i);
    }
    menu.addMenuListener(new MenuListener() {
        @Override
        public void menuSelected(MenuEvent e) {
            //System.out.println("EntitiesPanel:getConextMenu:menu selected");
            menu.removeAll();
            if (mia != null) {
                for (JMenuItem mi : mia)
                    menu.add(mi);
                menu.addSeparator();
            }
            JMenuItem refreshItem = new JMenuItem("Refresh");
            refreshItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    JConsoleHandler.execute(console, locator$);
                }
            });
            menu.add(refreshItem);
            JMenuItem openItem = new JMenuItem("Open folder");
            openItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        File folder = new File(entihome$ + "/" + entityKey$);
                        if (!folder.exists())
                            folder.mkdir();
                        Desktop.getDesktop().open(folder);
                    } catch (Exception ee) {
                        LOGGER.severe(ee.toString());
                    }
                }
            });
            menu.add(openItem);
            JMenuItem importItem = new JMenuItem("Import");
            importItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        File home = new File(System.getProperty("user.home"));
                        Desktop.getDesktop().open(home);
                    } catch (Exception ee) {
                        LOGGER.severe(ee.toString());
                    }
                }
            });

            menu.add(importItem);
            JMenuItem newItem = new JMenuItem("New text");
            newItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        JTextEditor textEditor = new JTextEditor();
                        String teLocator$ = textEditor.getLocator();
                        teLocator$ = Locator.append(teLocator$, Entigrator.ENTIHOME, entihome$);
                        String text$ = "New" + Identity.key().substring(0, 4) + ".txt";
                        teLocator$ = Locator.append(teLocator$, JTextEditor.TEXT, text$);
                        JFolderPanel fp = new JFolderPanel();
                        String fpLocator$ = fp.getLocator();
                        fpLocator$ = Locator.append(fpLocator$, Entigrator.ENTIHOME, entihome$);
                        fpLocator$ = Locator.append(fpLocator$, EntityHandler.ENTITY_KEY, entityKey$);
                        fpLocator$ = Locator.append(fpLocator$, BaseHandler.HANDLER_METHOD, "response");
                        fpLocator$ = Locator.append(fpLocator$, JRequester.REQUESTER_ACTION,
                                ACTION_CREATE_FILE);
                        String requesterResponseLocator$ = Locator.compressText(fpLocator$);
                        teLocator$ = Locator.append(teLocator$, JRequester.REQUESTER_RESPONSE_LOCATOR,
                                requesterResponseLocator$);
                        JConsoleHandler.execute(console, teLocator$);
                    } catch (Exception ee) {
                        LOGGER.severe(ee.toString());
                    }
                }
            });

            menu.add(newItem);
            //menu.addSeparator();
            if (hasToInsert()) {
                menu.addSeparator();
                JMenuItem insertItem = new JMenuItem("Insert");
                insertItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        try {
                            Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
                            Transferable clipboardContents = systemClipboard.getContents(null);
                            if (clipboardContents == null)
                                return;
                            Object transferData = clipboardContents
                                    .getTransferData(DataFlavor.javaFileListFlavor);
                            List<File> files = (List<File>) transferData;
                            for (int i = 0; i < files.size(); i++) {
                                File file = (File) files.get(i);
                                if (file.exists() && file.isFile()) {
                                    System.out.println("FolderPanel:insert:in=" + file.getPath());
                                    File dir = new File(entihome$ + "/" + entityKey$);
                                    if (!dir.exists())
                                        dir.mkdir();
                                    File out = new File(entihome$ + "/" + entityKey$ + "/" + file.getName());
                                    if (!out.exists())
                                        out.createNewFile();
                                    System.out.println("FolderPanel:insert:out=" + out.getPath());
                                    FileExpert.copyFile(file, out);
                                    JConsoleHandler.execute(console, getLocator());
                                }

                                //      System.out.println("FolderPanel:import:file="+file.getPath());
                            }
                        } catch (Exception ee) {
                            LOGGER.severe(ee.toString());

                        }

                    }
                });
                menu.add(insertItem);
            }
            if (hasToPaste()) {
                menu.addSeparator();
                JMenuItem pasteItem = new JMenuItem("Paste");
                pasteItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        String[] sa = console.clipboard.getContent();
                        Properties locator;
                        String file$;
                        File file;
                        File target;
                        String dir$ = entihome$ + "/" + entityKey$;
                        File dir = new File(dir$);
                        if (!dir.exists())
                            dir.mkdir();
                        for (String aSa : sa) {
                            try {
                                locator = Locator.toProperties(aSa);
                                if (LOCATOR_TYPE_FILE.equals(locator.getProperty(Locator.LOCATOR_TYPE))) {
                                    file$ = locator.getProperty(FILE_PATH);
                                    file = new File(file$);
                                    target = new File(dir$ + "/" + file.getName());
                                    if (!target.exists())
                                        target.createNewFile();
                                    FileExpert.copyFile(file, target);
                                }
                            } catch (Exception ee) {
                                LOGGER.info(ee.toString());
                            }
                        }
                        JConsoleHandler.execute(console, locator$);
                    }
                });
                menu.add(pasteItem);
            }
            if (hasSelectedItems()) {
                menu.addSeparator();
                JMenuItem deleteItem = new JMenuItem("Delete");
                deleteItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        int response = JOptionPane.showConfirmDialog(console.getContentPanel(), "Delete ?",
                                "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                        if (response == JOptionPane.YES_OPTION) {
                            String[] sa = JFolderPanel.this.listSelectedItems();
                            if (sa == null)
                                return;
                            Properties locator;
                            String file$;
                            File file;
                            for (String aSa : sa) {
                                locator = Locator.toProperties(aSa);
                                file$ = locator.getProperty(FILE_PATH);
                                file = new File(file$);
                                try {
                                    if (file.isDirectory())
                                        FileExpert.clear(file$);
                                    file.delete();
                                } catch (Exception ee) {
                                    LOGGER.info(ee.toString());
                                }
                            }
                        }
                        JConsoleHandler.execute(console, locator$);
                    }
                });
                menu.add(deleteItem);
                JMenuItem copyItem = new JMenuItem("Copy");
                copyItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        String[] sa = JFolderPanel.this.listSelectedItems();
                        console.clipboard.clear();
                        if (sa != null)
                            for (String aSa : sa)
                                console.clipboard.putString(aSa);
                    }
                });
                menu.add(copyItem);
                JMenuItem exportItem = new JMenuItem("Export");
                exportItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        try {
                            String[] sa = JFolderPanel.this.listSelectedItems();
                            Properties locator;
                            String file$;
                            File file;
                            ArrayList<File> fileList = new ArrayList<File>();
                            for (String aSa : sa) {
                                try {
                                    locator = Locator.toProperties(aSa);
                                    file$ = locator.getProperty(FILE_PATH);
                                    file = new File(file$);
                                    fileList.add(file);
                                } catch (Exception ee) {
                                    LOGGER.severe(ee.toString());
                                }
                            }
                            File[] fa = fileList.toArray(new File[0]);
                            if (fa.length < 1)
                                return;
                            //                             System.out.println("Folderpanel:finish:list="+fa.length);
                            JFileChooser chooser = new JFileChooser();
                            chooser.setCurrentDirectory(new java.io.File(System.getProperty("user.home")));
                            chooser.setDialogTitle("Export files");
                            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                            chooser.setAcceptAllFileFilterUsed(false);
                            if (chooser.showSaveDialog(JFolderPanel.this) == JFileChooser.APPROVE_OPTION) {
                                String dir$ = chooser.getSelectedFile().getPath();
                                File target;
                                for (File f : fa) {
                                    target = new File(dir$ + "/" + f.getName());
                                    if (!target.exists())
                                        target.createNewFile();
                                    FileExpert.copyFile(f, target);
                                }
                            } else {
                                Logger.getLogger(JMainConsole.class.getName()).info(" no selection");
                            }
                            //                            System.out.println("Folderpanel:finish:list="+fileList.size());  
                        } catch (Exception eee) {
                            LOGGER.severe(eee.toString());
                        }
                    }
                });
                menu.add(exportItem);
            }
        }

        @Override
        public void menuDeselected(MenuEvent e) {
        }

        @Override
        public void menuCanceled(MenuEvent e) {
        }
    });
    return menu;
}