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:parser.esperanto.gui.FileInputPanel.java

private void btnOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Szvegfjl (*.txt)", "txt");
    fileChooser.addChoosableFileFilter(filter);
    fileChooser.setCurrentDirectory(new File("./src/main/resources/text/"));

    int result = fileChooser.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
        String path = fileChooser.getSelectedFile().getAbsolutePath();
        try {/*w w w. j  av  a 2  s . co  m*/
            readFile(path);
            setOutput();
        } catch (FileNotFoundException ex) {
            JOptionPane.showMessageDialog(this, "A fjl nem tallhat");
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "Beolvassi hiba");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, e.getMessage());
        }
    }
}

From source file:pcgen.gui2.converter.panel.WriteDirectoryPanel.java

@Override
public void setupDisplay(JPanel panel, final CDOMObject pc) {
    panel.setLayout(layout);/*from  ww w  .j av  a 2 s .  c  o m*/
    Component label = new JLabel("Please select the Directory where Converted files should be written: ");
    AbstractButton button = new JButton("Browse...");
    button.setMnemonic('r');
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser chooser = new JFileChooser();
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            chooser.setDialogType(JFileChooser.OPEN_DIALOG);
            chooser.setCurrentDirectory(path.getParentFile());
            chooser.setSelectedFile(path);
            while (true) {
                int open = chooser.showOpenDialog(null);
                if (open == JFileChooser.APPROVE_OPTION) {
                    File fileToOpen = chooser.getSelectedFile();
                    if (fileToOpen.isDirectory() && fileToOpen.canRead() && fileToOpen.canWrite()) {
                        path = fileToOpen;
                        pc.put(ObjectKey.WRITE_DIRECTORY, path);
                        fileLabel.setText(path.getAbsolutePath());
                        PCGenSettings context = PCGenSettings.getInstance();
                        context.setProperty(PCGenSettings.CONVERT_OUTPUT_SAVE_PATH, path.getAbsolutePath());
                        showWarning();
                        break;
                    }
                    JOptionPane.showMessageDialog(null,
                            "Selection must be a valid " + "(readable & writeable) Directory");
                    chooser.setCurrentDirectory(path.getParentFile());
                } else if (open == JFileChooser.CANCEL_OPTION) {
                    break;
                }
            }
        }
    });
    panel.add(label);
    panel.add(fileLabel);
    panel.add(button);
    panel.add(warningLabel);
    showWarning();
    layout.putConstraint(SpringLayout.NORTH, label, 50, SpringLayout.NORTH, panel);
    layout.putConstraint(SpringLayout.NORTH, fileLabel, 75 + label.getPreferredSize().height,
            SpringLayout.NORTH, panel);
    layout.putConstraint(SpringLayout.NORTH, button, 75 + label.getPreferredSize().height, SpringLayout.NORTH,
            panel);
    layout.putConstraint(SpringLayout.WEST, label, 25, SpringLayout.WEST, panel);
    layout.putConstraint(SpringLayout.WEST, fileLabel, 25, SpringLayout.WEST, panel);
    layout.putConstraint(SpringLayout.EAST, button, -50, SpringLayout.EAST, panel);
    layout.putConstraint(SpringLayout.NORTH, warningLabel, 20, SpringLayout.SOUTH, fileLabel);
    layout.putConstraint(SpringLayout.WEST, warningLabel, 25, SpringLayout.WEST, panel);

    fileLabel.setText(path.getAbsolutePath());
}

From source file:pcgen.gui2.dialog.ExportDialog.java

private void export(boolean pdf) {
    UIPropertyContext context = UIPropertyContext.createContext("ExportDialog");
    final JFileChooser fcExport = new JFileChooser();
    fcExport.setFileSelectionMode(JFileChooser.FILES_ONLY);
    File baseDir = null;/*from   w w w. j  ava 2s . c o m*/
    {
        String path;
        if (pdf) {
            path = context.getProperty(PDF_EXPORT_DIR_PROP);
        } else {
            path = context.getProperty(HTML_EXPORT_DIR_PROP);
        }
        if (path != null) {
            baseDir = new File(path);
        }
    }
    if (baseDir == null || !baseDir.isDirectory()) {
        baseDir = SystemUtils.getUserHome();
    }
    fcExport.setCurrentDirectory(baseDir);

    URI uri = fileList.getSelectedValue();
    String extension = ExportUtilities.getOutputExtension(uri.toString(), pdf);
    if (pdf) {
        FileFilter fileFilter = new FileNameExtensionFilter("PDF Documents (*.pdf)", "pdf");
        fcExport.addChoosableFileFilter(fileFilter);
        fcExport.setFileFilter(fileFilter);
    } else if ("htm".equalsIgnoreCase(extension) || "html".equalsIgnoreCase(extension)) {
        FileFilter fileFilter = new FileNameExtensionFilter("HTML Documents (*.htm, *.html)", "htm", "html");
        fcExport.addChoosableFileFilter(fileFilter);
        fcExport.setFileFilter(fileFilter);
    } else if ("xml".equalsIgnoreCase(extension)) {
        FileFilter fileFilter = new FileNameExtensionFilter("XML Documents (*.xml)", "xml");
        fcExport.addChoosableFileFilter(fileFilter);
        fcExport.setFileFilter(fileFilter);
    } else {
        String desc = extension + " Files (*." + extension + ")";
        fcExport.addChoosableFileFilter(new FileNameExtensionFilter(desc, extension));
    }
    String name;
    File path;
    if (!partyBox.isSelected()) {
        CharacterFacade character = (CharacterFacade) characterBox.getSelectedItem();
        path = character.getFileRef().get();
        if (path != null) {
            path = path.getParentFile();
        } else {
            path = new File(PCGenSettings.getPcgDir());
        }
        name = character.getTabNameRef().get();
        if (StringUtils.isEmpty(name)) {
            name = character.getNameRef().get();
        }
    } else {
        path = new File(PCGenSettings.getPcgDir());
        name = "Entire Party";
    }
    if (pdf) {
        fcExport.setSelectedFile(new File(path, name + ".pdf"));
    } else {
        fcExport.setSelectedFile(new File(path, name + "." + extension));
    }
    fcExport.setDialogTitle("Export " + name);
    if (fcExport.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) {
        return;
    }

    final File outFile = fcExport.getSelectedFile();
    if (pdf) {
        context.setProperty(PDF_EXPORT_DIR_PROP, outFile.getParent());
    } else {
        context.setProperty(HTML_EXPORT_DIR_PROP, outFile.getParent());
    }

    if (StringUtils.isEmpty(outFile.getName())) {
        pcgenFrame.showErrorMessage("PCGen", "You must set a filename.");
        return;
    }

    if (outFile.isDirectory()) {
        pcgenFrame.showErrorMessage("PCGen", "You cannot overwrite a directory with a file.");
        return;
    }

    if (outFile.exists() && !SettingsHandler.getAlwaysOverwrite()) {
        int reallyClose = JOptionPane.showConfirmDialog(this,
                "The file " + outFile.getName() + " already exists, are you sure you want to overwrite it?",
                "Confirm overwriting " + outFile.getName(), JOptionPane.YES_NO_OPTION);

        if (reallyClose != JOptionPane.YES_OPTION) {
            return;
        }
    }
    if (pdf) {
        new PDFExporter(outFile, extension, name).execute();
    } else {
        if (!printToFile(outFile)) {
            String message = "The character export failed. Please see the log for details.";
            pcgenFrame.showErrorMessage(Constants.APPLICATION_NAME, message);
            return;
        }
        maybeOpenFile(outFile);
        Globals.executePostExportCommandStandard(outFile.getAbsolutePath());
    }
}

From source file:pcgen.gui2.facade.SpellSupportFacadeImpl.java

@Override
public void exportSpells() {
    final String template = PCGenSettings.getInstance().getProperty(PCGenSettings.SELECTED_SPELL_SHEET_PATH);
    if (StringUtils.isEmpty(template)) {
        delegate.showErrorMessage(Constants.APPLICATION_NAME, LanguageBundle.getString("in_spellNoSheet")); //$NON-NLS-1$
        return;/*  ww  w. j a  va  2  s .com*/
    }
    String ext = template.substring(template.lastIndexOf('.'));

    // Get the name of the file to output to.
    JFileChooser fcExport = new JFileChooser();
    fcExport.setCurrentDirectory(new File(PCGenSettings.getPcgDir()));
    fcExport.setDialogTitle(
            LanguageBundle.getString("InfoSpells.export.spells.for") + charDisplay.getDisplayName()); //$NON-NLS-1$

    if (fcExport.showSaveDialog(null) != JFileChooser.APPROVE_OPTION) {
        return;
    }
    final String aFileName = fcExport.getSelectedFile().getAbsolutePath();
    if (aFileName.length() < 1) {
        delegate.showErrorMessage(Constants.APPLICATION_NAME,
                LanguageBundle.getString("InfoSpells.must.set.filename")); //$NON-NLS-1$ 
        return;
    }

    try {
        final File outFile = new File(aFileName);

        if (outFile.isDirectory()) {
            delegate.showErrorMessage(Constants.APPLICATION_NAME,
                    LanguageBundle.getString("InfoSpells.can.not.overwrite.directory")); //$NON-NLS-1$ 
            return;
        }

        if (outFile.exists()) {
            int reallyClose = JOptionPane.showConfirmDialog(null,
                    LanguageBundle.getFormattedString("InfoSpells.confirm.overwrite", outFile.getName()), //$NON-NLS-1$
                    LanguageBundle.getFormattedString("InfoSpells.overwriting", //$NON-NLS-1$
                            outFile.getName()),
                    JOptionPane.YES_NO_OPTION);

            if (reallyClose != JOptionPane.YES_OPTION) {
                return;
            }
        }

        // Output the file
        File templateFile = new File(template);
        boolean success;
        if (ExportUtilities.isPdfTemplate(templateFile)) {
            success = BatchExporter.exportCharacterToPDF(pcFacade, outFile, templateFile);
        } else {
            success = BatchExporter.exportCharacterToNonPDF(pcFacade, outFile, templateFile);
        }

        if (!success) {
            delegate.showErrorMessage(Constants.APPLICATION_NAME, LanguageBundle
                    .getFormattedString("InfoSpells.export.failed", charDisplay.getDisplayName())); //$NON-NLS-1$ 
        }
    } catch (Exception ex) {
        Logging.errorPrint(
                LanguageBundle.getFormattedString("InfoSpells.export.failed", charDisplay.getDisplayName()), //$NON-NLS-1$
                ex);
        delegate.showErrorMessage(Constants.APPLICATION_NAME, LanguageBundle
                .getFormattedString("InfoSpells.export.failed.retry", charDisplay.getDisplayName())); //$NON-NLS-1$ 
    }
}

From source file:pcgen.gui2.prefs.LookAndFeelPanel.java

private void selectThemePack() {
    JFileChooser fc = new JFileChooser(ConfigurationSettings.getThemePackDir());
    fc.setDialogTitle(LanguageBundle.getString("in_Prefs_chooseSkinDialogTitle"));

    String theme = LookAndFeelManager.getCurrentThemePack();

    if (StringUtils.isNotEmpty(theme)) {
        fc.setCurrentDirectory(new File(LookAndFeelManager.getCurrentThemePack()));
        fc.setSelectedFile(new File(LookAndFeelManager.getCurrentThemePack()));
    }/*  w w w  . j  a  va  2s.c  o m*/

    fc.addChoosableFileFilter(new ThemePackFilter());

    if (fc.showOpenDialog(getParent().getParent()) == JFileChooser.APPROVE_OPTION) //ugly, but it works
    {
        File newTheme = fc.getSelectedFile();

        if (newTheme.isDirectory() || (!newTheme.getName().endsWith("themepack.zip"))) {
            ShowMessageDelegate.showMessageDialog(LanguageBundle.getString("in_Prefs_notAThemeErrorItem"),
                    Constants.APPLICATION_NAME, MessageType.ERROR);
        } else {
            LookAndFeelManager.setSelectedThemePack(newTheme.getAbsolutePath());
        }
    }
}

From source file:pcgen.gui2.tools.DesktopBrowserLauncher.java

/**
 * Sets the default browser.// w  w  w.j  a  v  a  2  s .c  om
 */
public static void selectDefaultBrowser() {
    final JFileChooser fc = new JFileChooser();
    fc.setDialogTitle("Find and select your preferred html browser.");

    if (SystemUtils.IS_OS_MAC || SystemUtils.IS_OS_MAC_OSX) {
        fc.putClientProperty("JFileChooser.appBundleIsTraversable", "never");
    }

    if (PCGenSettings.getBrowserPath() != null) {
        fc.setCurrentDirectory(new File(PCGenSettings.getBrowserPath()));
    }

    final int returnVal = fc.showOpenDialog(null);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        final File file = fc.getSelectedFile();
        PCGenSettings.OPTIONS_CONTEXT.setProperty(PCGenSettings.BROWSER_PATH, file.getAbsolutePath());
    }
}

From source file:pcgen.gui2.tools.Utility.java

/**
 * Sets the default browser./*www.j a va2s .co m*/
 *
 * @param parent The component to show the dialog over.
 */
public static void selectDefaultBrowser(Component parent) {
    final JFileChooser fc = new JFileChooser();
    fc.setDialogTitle("Find and select your preferred html browser.");

    if (SystemUtils.IS_OS_MAC || SystemUtils.IS_OS_MAC_OSX) {
        // On MacOS X, do not traverse file bundles
        fc.putClientProperty("JFileChooser.appBundleIsTraversable", "never");
    }

    if (PCGenSettings.getBrowserPath() == null) {
        //No action, as we have no idea what a good default would be...
    } else {
        fc.setCurrentDirectory(new File(PCGenSettings.getBrowserPath()));
    }

    final int returnVal = fc.showOpenDialog(parent);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        final File file = fc.getSelectedFile();
        PCGenSettings.OPTIONS_CONTEXT.setProperty(PCGenSettings.BROWSER_PATH, file.getAbsolutePath());
    }
}

From source file:pcgui.SetupParametersPanel.java

/**
 * Create the frame./*from  w  ww.j a  v  a  2  s. co m*/
 * 
 * @param switcher
 * 
 * @param rootFrame
 */

public SetupParametersPanel(final PanelSwitcher switcher, JFrame rootFrame) {
    this.rootFrame = rootFrame;
    setLayout(new BorderLayout());

    JLabel headingLabel = new JLabel("Setup Parameters");
    headingLabel.setFont(new Font("Tahoma", Font.BOLD, 16));
    add(headingLabel, BorderLayout.NORTH);
    JButton saveBtn = new JButton("Save");
    final JButton runModifiedBtn = new JButton("Run");

    runModifiedBtn.setEnabled(false);

    runModifiedBtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            runModel();

        }
    });

    saveBtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            //creating separate copy of model so that changes in one doesn't effect other
            ArrayList<ArrayList<Object>> mod = new ArrayList<ArrayList<Object>>(model.getData());
            //call save model of modelsaver
            //TODO add visualization list and save to excel using similar method as below
            //TODO add modelname, should contain .xls/.xlsx extension
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_hhmmss");
            outputFile = importedFile.toString().replace(".mos", "") + "_" + sdf.format(new Date())
                    + "_FEORA_solution.xlsx";
            ModelSaver.saveInputModel(mod, outputFile);

            runModifiedBtn.setEnabled(true);

        }
    });

    JLabel label = new JLabel("Enter count of random value runs");
    repeatCount = new JTextField();
    repeatCount.setToolTipText("Enter count for which each combination of step variables is run ");
    repeatCount.setText("1");
    repeatCount.setPreferredSize(new Dimension(100, 20));

    JPanel runConfig = new JPanel();
    runConfig.setLayout(new GridLayout(2, 2));

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridwidth = GridBagConstraints.CENTER;

    JPanel configCount = new JPanel(new FlowLayout());
    JPanel configButtons = new JPanel(new FlowLayout());
    configCount.add(label);
    configCount.add(repeatCount);

    JButton btnLoadSavedConfiguration = new JButton("Load Saved Configuration");
    btnLoadSavedConfiguration.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser jFileChooser = new JFileChooser();

            File workingDirectory = new File(System.getProperty("user.dir"));

            jFileChooser.setCurrentDirectory(workingDirectory);

            jFileChooser.setFileFilter(new FileFilter() {

                @Override
                public String getDescription() {
                    // TODO Auto-generated method stub
                    return "Excel solution files";
                }

                @Override
                public boolean accept(File f) {
                    // TODO Auto-generated method stub
                    return f.isDirectory() || f.getName().endsWith(".xls") || f.getName().endsWith(".xlsx");

                }
            });
            int returnVal = jFileChooser.showOpenDialog(null);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = jFileChooser.getSelectedFile();

                // This is where a real application would open the file.

                if (file.getName().endsWith(".xls") || file.getName().endsWith(".xlsx")) {
                    String fileName = file.getAbsolutePath();
                    List<List<String>> savedConfig = ModelSaver.loadInputConfigFromExcel(fileName);
                    ArrayList<Symbol> symList = new ArrayList<Symbol>();

                    int i = 0;
                    for (List<String> list : savedConfig) {
                        //ignore the header row
                        if (i > 0) {
                            System.out.println("VariableName=" + list.get(0));
                            System.out.println("Datatype=" + list.get(1));
                            System.out.println("Type=" + list.get(2));
                            System.out.println("Value=" + list.get(3));
                            System.out.println("ExternalFile=" + list.get(4));
                            System.out.println("ExcelRange=" + list.get(5));
                            System.out.println("DistributionFunction=" + list.get(6));
                            System.out.println("OutputTracket=" + list.get(7));
                            Symbol sym = new Symbol<>();
                            sym.name = list.get(0);
                            sym.typeString = list.get(1);
                            sym.mode = list.get(2);
                            sym.set(list.get(3));
                            sym.externalFile = list.get(4);
                            sym.excelFileRange = list.get(5);
                            sym.distFunction = list.get(6);
                            sym.trackingEnabled = Boolean.parseBoolean(list.get(7));
                            symList.add(sym);
                        }
                        i++;

                    }
                    initParamList(symList, parser);
                }

            } else {
                //               System.out.println("Open command cancelled by user.");
            }

        }
    });
    configButtons.add(btnLoadSavedConfiguration);

    configButtons.add(saveBtn);
    configButtons.add(runModifiedBtn);
    runConfig.add(configCount);
    runConfig.add(configButtons);
    add(runConfig, BorderLayout.SOUTH);

    setVisible(true);
}

From source file:pdfreader.PDFReader.java

private void openMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
    listOfSelectedRegionInRectangle = new ArrayList<TaggedRegion>();
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(currentDir);

    ExtensionFileFilter pdfFilter = new ExtensionFileFilter(new String[] { "PDF" }, "PDF Files");
    chooser.setFileFilter(pdfFilter);//from   www.ja v a 2s .c o  m
    int result = chooser.showOpenDialog(PDFReader.this);
    if (result == JFileChooser.APPROVE_OPTION) {
        name = chooser.getSelectedFile().getPath();
        System.out.println(name);
        nameOfFile = chooser.getSelectedFile().getName();
        currentDir = new File(name).getParentFile();
        try {
            openPDFFile("");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:phex.gui.common.FileDialogHandler.java

private static JFileChooser initDefaultChooser(String title, String approveBtnText, char approveBtnMnemonic,
        FileFilter filter, int mode, File currentDirectory, String notifyPopupTitle,
        String notifyPopupShortMessage) {
    JFileChooser chooser = new JFileChooser();

    if (notifyPopupTitle != null || notifyPopupShortMessage != null) {
        displayNotificationPopup(chooser, notifyPopupTitle, notifyPopupShortMessage);
    }/* ww  w .j  a va  2s.  com*/

    if (currentDirectory != null) {
        chooser.setCurrentDirectory(currentDirectory);
    }
    if (filter != null) {
        chooser.setFileFilter(filter);
    }
    chooser.setFileSelectionMode(mode);
    chooser.setDialogTitle(title);
    chooser.setApproveButtonText(approveBtnText);
    chooser.setApproveButtonMnemonic(approveBtnMnemonic);
    return chooser;
}