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:org.sleuthkit.autopsy.experimental.autoingest.FileExporterSettingsPanel.java

/**
 * Validates that the selected folder exists, and sets the passed-in
 * textField to empty if it does not exist. Then checks if the sanitized
 * folder is readable and writable with the current user's credentials,
 * returning True if so and False if not. This has the desirable effect that
 * a folder can show up in the text box (as chosen by the user while
 * browsing), and still return false if the permissions are incorrect. This
 * way the user can see the folder chosen and take appropriate action to fix
 * the permissions. Use this only for files chosen by the file chooser.
 *
 * @param fileChooser The fileChooser we want to use.
 * @param textField   The text field to store the sanitized value in.
 *
 * Throws FolderDidNotValidateException/* www. j  a  v  a  2s .  c o  m*/
 */
private void validateAndSanitizeBrowsedDirectory(JFileChooser fileChooser, JTextField textField)
        throws FolderDidNotValidateException {
    File selectedFile = fileChooser.getSelectedFile();
    if (selectedFile == null || !selectedFile.exists()) {
        textField.setText(""); //NON-NLS

        throw new FolderDidNotValidateException(NbBundle.getMessage(FileExporterSettingsPanel.class,
                "FileExporterSettingsPanel.UnableToFindDirectory"));

    } else {
        textField.setText(selectedFile.toString());
        File file = new File(selectedFile.toString());
        fileChooser.setCurrentDirectory(file);

        if (!FileUtil.hasReadWriteAccess(file.toPath())) {
            throw new FolderDidNotValidateException(NbBundle.getMessage(FileExporterSettingsPanel.class,
                    "FileExporterSettingsPanel.PermissionsInvalid"));
        }
    }
}

From source file:org.sonar.scanner.protocol.viewer.ScannerReportViewerApp.java

private void loadReport() {
    final JFileChooser fc = new JFileChooser();
    fc.setDialogTitle("Choose scanner report directory");
    File lastReport = getLastUsedReport();
    if (lastReport != null) {
        fc.setCurrentDirectory(lastReport);
    }/*from w  ww . j  av  a2  s  . com*/
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    fc.setFileHidingEnabled(false);
    fc.setApproveButtonText("Open scanner report");
    int returnVal = fc.showOpenDialog(frame);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        try {
            setLastUsedReport(file);
            loadReport(file);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(frame, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            exit();
        }
    } else {
        exit();
    }

}

From source file:org.tinymediamanager.ui.TmmUIHelper.java

private static Path openJFileChooser(int mode, String dialogTitle, boolean open, String filename,
        FileNameExtensionFilter filter) {
    JFileChooser fileChooser;
    // are we forced to open the legacy file chooser?
    if ("true".equals(System.getProperty("tmm.legacy.filechooser"))) {
        fileChooser = new JFileChooser();
    } else {/*from ww w .  ja  va 2s .  co  m*/
        fileChooser = new NativeFileChooser();
    }

    fileChooser.setFileSelectionMode(mode);
    if (lastDir != null) {
        fileChooser.setCurrentDirectory(lastDir.toFile());
    }
    fileChooser.setDialogTitle(dialogTitle);

    int result = -1;
    if (open) {
        result = fileChooser.showOpenDialog(MainWindow.getFrame());
    } else {
        if (StringUtils.isNotBlank(filename)) {
            fileChooser.setSelectedFile(new File(filename));
            fileChooser.setFileFilter(filter);
        }
        result = fileChooser.showSaveDialog(MainWindow.getFrame());
    }

    if (result == JFileChooser.APPROVE_OPTION) {
        if (mode == JFileChooser.DIRECTORIES_ONLY) {
            lastDir = fileChooser.getSelectedFile().toPath();
        } else {
            lastDir = fileChooser.getSelectedFile().getParentFile().toPath();
        }
        return fileChooser.getSelectedFile().toPath();
    }

    return null;
}

From source file:org.tmpotter.ui.ActionHandler.java

/**
 * Save project as specified filename./*from  www.j a  va  2 s  .  c  o m*/
 */
private void saveProjectAs() {
    File outFile = new File(modelMediator.getProjectName().concat(".tmpx"));
    try {
        boolean save = false;
        boolean cancel = false;
        while (!save && !cancel) {
            final JFileChooser fc = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("TMX File", "tmpx");
            fc.setFileFilter(filter);
            boolean nameOfUser = false;
            while (!nameOfUser) {
                fc.setLocation(230, 300);
                fc.setCurrentDirectory(RuntimePreferences.getUserHome());
                fc.setDialogTitle(getString("DLG.SAVEAS"));
                fc.setMultiSelectionEnabled(false);
                fc.setSelectedFile(outFile);
                fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
                RuntimePreferences.setUserHome(fc.getCurrentDirectory());
                int returnVal;
                returnVal = fc.showSaveDialog(parent);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    outFile = fc.getSelectedFile();
                    if (!outFile.getName().endsWith(".tmpx")) {
                        outFile = new File(outFile.getName().concat(".tmpx"));
                    }
                    nameOfUser = true;
                } else {
                    nameOfUser = true;
                    cancel = true;
                }
            }
            int selected;
            if (nameOfUser && !cancel) {
                if (outFile.exists()) {
                    final Object[] options = { getString("BTN.SAVE"), getString("BTN.CANCEL") };
                    selected = JOptionPane.showOptionDialog(parent, getString("MSG.FILE_EXISTS"),
                            getString("MSG.WARNING"), JOptionPane.OK_CANCEL_OPTION,
                            JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
                    if (selected == 0) {
                        save = true;
                    }
                } else {
                    save = true;
                }
            }
        }
        if (save) {
            cleanTmData();
            ProjectProperties prop = modelMediator.getProjectProperties();
            prop.setFilePathProject(outFile);
            TmxpWriter.writeTmxp(prop, tmData.getDocumentOriginal(), tmData.getDocumentTranslation());
        }
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(parent, JOptionPane.ERROR_MESSAGE);
    }
}

From source file:org.tmpotter.ui.ActionHandler.java

/**
 * Action entry points./* w  w  w .ja v  a 2s.c  o  m*/
 * <p>
 * All action entry points named with +ActionPerformed().
 */
public void onFileOpen() {
    final JFileChooser fc = new JFileChooser();
    File filePath = RuntimePreferences.getUserHome();
    fc.setCurrentDirectory(filePath);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Project File(.tmpx)", "tmpx");
    fc.setFileFilter(filter);
    fc.setMultiSelectionEnabled(false);
    final int returnVal = fc.showOpenDialog(parent);
    filePath = fc.getCurrentDirectory();
    RuntimePreferences.setUserHome(filePath);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        filePath = fc.getSelectedFile();

        if (filePath.getName().endsWith(".tmpx") && filePath.exists()) {
            try {
                final FileInputStream fr = new FileInputStream(filePath);
                fr.close();
                onOpenFile(filePath);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(parent, getString("MSG.ERROR.FILE_NOTFOUND"),
                        getString("MSG.ERROR"), JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(parent, getString("MSG.ERROR.FILE_NOTFOUND"), getString("MSG.ERROR"),
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:org.tros.logo.swing.LogoMenuBar.java

/**
 * Set up the export menu./*from   www  .j av  a 2  s.c  o m*/
 *
 * @return
 */
private JMenu setupExportMenu() {
    JMenu exportMenu = new JMenu(Localization.getLocalizedString("ExportMenu"));

    JMenuItem exportGif = new JMenuItem(Localization.getLocalizedString("ExportGIF"));
    JMenuItem exportPng = new JMenuItem(Localization.getLocalizedString("ExportPNG"));
    JMenuItem exportSvg = new JMenuItem(Localization.getLocalizedString("ExportSVG"));

    exportSvg.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(false);
            java.util.prefs.Preferences prefs = java.util.prefs.Preferences
                    .userNodeForPackage(LogoMenuBar.class);
            chooser.setCurrentDirectory(new File(prefs.get("export-directory", ".")));

            chooser.setVisible(true);
            int result = chooser.showSaveDialog(parent);

            if (result == JFileChooser.APPROVE_OPTION) {
                String filename = chooser.getSelectedFile().getPath();
                prefs.put("export-directory", chooser.getSelectedFile().getParent());
                if (Drawable.class.isAssignableFrom(canvas.getClass())) {
                    try (FileOutputStream fos = new FileOutputStream(new File(filename))) {
                        generateSVG((Drawable) canvas, fos);
                        fos.flush();
                    } catch (IOException ex) {
                        org.tros.utils.logging.Logging.getLogFactory().getLogger(LogoMenuBar.class).warn(null,
                                ex);
                    }
                }
            }
        }
    });

    exportGif.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(false);
            java.util.prefs.Preferences prefs = java.util.prefs.Preferences
                    .userNodeForPackage(LogoMenuBar.class);
            chooser.setCurrentDirectory(new File(prefs.get("export-directory", ".")));

            chooser.setVisible(true);
            int result = chooser.showSaveDialog(parent);

            if (result == JFileChooser.APPROVE_OPTION) {
                final String filename = chooser.getSelectedFile().getPath();
                prefs.put("export-directory", chooser.getSelectedFile().getParent());
                Thread t = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (Drawable.class.isAssignableFrom(canvas.getClass())
                                && BufferedImageProvider.class.isAssignableFrom((canvas.getClass()))) {
                            try {
                                generateGIF(((Drawable) canvas).cloneDrawable(), (BufferedImageProvider) canvas,
                                        filename);
                            } catch (SVGGraphics2DIOException ex) {
                                Logger.getLogger(LogoMenuBar.class.getName()).log(Level.SEVERE, null, ex);
                            } catch (IOException ex) {
                                Logger.getLogger(LogoMenuBar.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                });
                t.setDaemon(true);
                t.start();
            }
        }
    });
    exportPng.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(false);
            java.util.prefs.Preferences prefs = java.util.prefs.Preferences
                    .userNodeForPackage(LogoMenuBar.class);
            chooser.setCurrentDirectory(new File(prefs.get("export-directory", ".")));

            chooser.setVisible(true);
            int result = chooser.showSaveDialog(parent);

            if (result == JFileChooser.APPROVE_OPTION) {
                String filename = chooser.getSelectedFile().getPath();
                prefs.put("export-directory", chooser.getSelectedFile().getParent());
                // retrieve image
                if (BufferedImageProvider.class.isAssignableFrom(canvas.getClass())) {
                    generatePNG((BufferedImageProvider) canvas, filename);
                }
            }
        }
    });

    exportMenu.add(exportSvg);
    exportMenu.add(exportGif);
    exportMenu.add(exportPng);
    exportMenu.setMnemonic('X');
    exportSvg.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.ALT_MASK));
    exportGif.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.ALT_MASK));
    exportPng.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, InputEvent.ALT_MASK));
    return (exportMenu);
}

From source file:org.tros.torgo.ControllerBase.java

/**
 * Open a file.//  w w w  . j  a va  2s.  c o  m
 */
@Override
public void openFile() {
    JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(false);
    java.util.prefs.Preferences prefs = java.util.prefs.Preferences.userNodeForPackage(ControllerBase.class);
    chooser.setCurrentDirectory(
            new File(prefs.get(ControllerBase.class.getName() + "-working-directory", ".")));

    if (chooser.showOpenDialog(window) == JFileChooser.APPROVE_OPTION) {
        filename = chooser.getSelectedFile().getPath();
        prefs.put(ControllerBase.class.getName() + "-working-directory", chooser.getSelectedFile().getParent());
        openFile(chooser.getSelectedFile());
    }
}

From source file:org.tros.torgo.ControllerBase.java

/**
 * Save the script as a new file.// w w  w . j  a  va 2 s  .c om
 */
@Override
public void saveFileAs() {
    JFileChooser chooser = new JFileChooser();
    chooser.setMultiSelectionEnabled(false);
    java.util.prefs.Preferences prefs = java.util.prefs.Preferences.userNodeForPackage(ControllerBase.class);
    chooser.setCurrentDirectory(
            new File(prefs.get(ControllerBase.class.getName() + "-working-directory", ".")));

    int result = chooser.showSaveDialog(window);

    if (result == JFileChooser.APPROVE_OPTION) {
        filename = chooser.getSelectedFile().getPath();
        prefs.put(ControllerBase.class.getName() + "-working-directory", chooser.getSelectedFile().getParent());
        saveFile();
    }
}

From source file:osu.beatmapdownloader.JFrame.java

private void B_DirectoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_B_DirectoryActionPerformed
       JFileChooser chooser;

       chooser = new JFileChooser();
       chooser.setCurrentDirectory(new java.io.File("."));
       chooser.setDialogTitle("Open Osu! Installation Directory");
       chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
       chooser.setAcceptAllFileFilterUsed(false);
       if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
           File route = chooser.getSelectedFile();
           if (route.toString().endsWith("Songs")) {
               Directory = route.getAbsolutePath();
               T_Directory.setText(Directory);
           } else {
               if (route.isDirectory()) {
                   String[] Files = route.list();
                   boolean found = false;
                   for (String f : Files)
                       if (f.contains("Songs")) {
                           Directory = route + File.separator + f;
                           T_Directory.setText(Directory);
                           set("SongDirectory", Directory);
                           found = true;
                           break;
                       }/*from w w w  .j a va2  s  .c  o  m*/
                   if (found == false)
                       Alert("Incorrect Osu! Directory");
               }
           }
       }
   }

From source file:paquete.HollywoodUI.java

private void btn_buscar_fotoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_buscar_fotoMouseClicked
    JFileChooser jfc = new JFileChooser();
    jfc.setCurrentDirectory(new File("./"));
    FileFilter filtro = new FileNameExtensionFilter("Jpg, Png", "jpg", "png");
    jfc.setFileFilter(filtro);/*from  w  w  w  .j  a v  a2s.c o m*/
    File archivo = null;
    try {
        int op = jfc.showOpenDialog(this.add_actor);
        if (op == JFileChooser.APPROVE_OPTION) {
            archivo = jfc.getSelectedFile();
        }
        BufferedImage imagen = ImageIO.read(archivo);
        Image img;
        img = Toolkit.getDefaultToolkit().createImage(imagen.getSource())
                .getScaledInstance(label_profile.getWidth(), label_profile.getHeight(), 0);
        label_profile.setIcon(new ImageIcon(img));
        this.temp.setFoto_actor(resize(imagen, 54, 54));
    } catch (Exception e) {
        JOptionPane.showMessageDialog(add_actor, "Error al intentar abrir archivo", "ERROR",
                JOptionPane.ERROR_MESSAGE);
    }
}