Example usage for javax.swing JFileChooser APPROVE_OPTION

List of usage examples for javax.swing JFileChooser APPROVE_OPTION

Introduction

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

Prototype

int APPROVE_OPTION

To view the source code for javax.swing JFileChooser APPROVE_OPTION.

Click Source Link

Document

Return value if approve (yes, ok) is chosen.

Usage

From source file:de.fionera.javamailer.gui.mainView.controllerMain.java

/**
 * Adds the Actionlisteners to the Mainview
 *
 * @param viewMain The Mainview/*from  ww  w .  j av  a  2s .  co  m*/
 */
private void addActionListener(viewMain viewMain) {
    /**
     * Changes the Amount in the AmountLabel when the slider is moved
     */
    viewMain.getSetMailSettingsPanel().getSliderAmountMails().addChangeListener(e -> {
        Main.amountMails = ((JSlider) e.getSource()).getValue();
        viewMain.getSetMailSettingsPanel().getLabelNumberAmountMails()
                .setText("" + ((JSlider) e.getSource()).getValue());
    });

    /**
     * Changes the Delay in the DelayLabel when the slider is moved
     */
    viewMain.getSetMailSettingsPanel().getSliderDelayMails().addChangeListener(e -> {
        Main.delayMails = ((JSlider) e.getSource()).getValue();
        viewMain.getSetMailSettingsPanel().getLabelNumberDelayMails()
                .setText("" + ((JSlider) e.getSource()).getValue());
    });

    /**
     * Closes the Program, when close is clicked
     */
    viewMain.getCloseItem().addActionListener(e -> System.exit(0));

    /**
     * Opens the Settings when the settingsbutton is clicked
     */
    viewMain.getSettingsItem().addActionListener(e -> new controllerSettings());

    /**
     * Save current Setup
     */
    viewMain.getSaveSettings().addActionListener(e -> {
        JFileChooser jChooser = new JFileChooser();
        JFrame parentFrame = new JFrame();

        FileNameExtensionFilter filter = new FileNameExtensionFilter("Setup file", "jms", "Blub");
        jChooser.setFileFilter(filter);

        jChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jChooser.setDialogTitle("Select Setup");

        int userSelection = jChooser.showSaveDialog(parentFrame);

        if (userSelection == JFileChooser.APPROVE_OPTION) {
            File fileToSave = new File(jChooser.getSelectedFile() + ".jms");

            saveSetup(viewMain, fileToSave, new ObjectMapper());
        }
    });

    /**
     * Load Setup
     */
    viewMain.getLoadSettings().addActionListener(e -> {
        JFileChooser jChooser = new JFileChooser();

        FileNameExtensionFilter filter = new FileNameExtensionFilter("Setup file", "jms", "Blub");
        jChooser.setFileFilter(filter);

        jChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jChooser.setDialogTitle("Select Setup");
        jChooser.showOpenDialog(null);

        File file = jChooser.getSelectedFile();

        if (file != null) {
            if (file.getName().endsWith("jms")) {
                try {
                    loadSetup(viewMain, file, new ObjectMapper());
                } catch (Exception error) {
                    error.printStackTrace();
                }
            }
        }
    });

    /**
     * Opens the Open File dialog and start the Parsing of it
     */
    viewMain.getSelectRecipientsPanel().getSelectExcelFileButton().addActionListener(e -> {
        DefaultTableModel model;
        JFileChooser jChooser = new JFileChooser();

        jChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        jChooser.addChoosableFileFilter(new FileNameExtensionFilter("Microsoft Excel 97 - 2003 (.xls)", "xls"));
        jChooser.addChoosableFileFilter(new FileNameExtensionFilter("Microsoft Excel (.xlsx)", "xlsx"));
        jChooser.setDialogTitle("Select only Excel workbooks");
        jChooser.showOpenDialog(null);
        File file = jChooser.getSelectedFile();
        if (file != null) {
            parseFilesForImport parseFilesForImport = new parseFilesForImport();

            if (file.getName().endsWith("xls")) {
                ArrayList returnedData = parseFilesForImport.parseXLSFile(file);

                model = new DefaultTableModel((String[][]) returnedData.get(0), (String[]) returnedData.get(1));

                int tableWidth = model.getColumnCount() * 150;
                int tableHeight = model.getRowCount() * 25;
                viewMain.getSelectRecipientsPanel().getTable()
                        .setPreferredSize(new Dimension(tableWidth, tableHeight));

            } else if (file.getName().endsWith("xlsx")) {
                ArrayList returnedData = parseFilesForImport.parseXLSXFile(file);

                model = new DefaultTableModel((String[][]) returnedData.get(0), (String[]) returnedData.get(1));

                int tableWidth = model.getColumnCount() * 150;
                int tableHeight = model.getRowCount() * 25;
                viewMain.getSelectRecipientsPanel().getTable()
                        .setPreferredSize(new Dimension(tableWidth, tableHeight));

            } else {
                JOptionPane.showMessageDialog(null, "Please select only Excel file.", "Error",
                        JOptionPane.ERROR_MESSAGE);

                model = new DefaultTableModel();
            }
        } else {
            model = new DefaultTableModel();

        }

        viewMain.getSelectRecipientsPanel().getTable().setModel(model);

        int tableWidth = model.getColumnCount() * 150;
        int tableHeight = model.getRowCount() * 25;
        viewMain.getSelectRecipientsPanel().getTable().setPreferredSize(new Dimension(tableWidth, tableHeight));
        viewMain.getCheckAllSettings().getLabelRecipientsAmount().setText("" + model.getRowCount());
        viewMain.getCheckAllSettings().getLabelTimeAmount()
                .setText(""
                        + viewMain.getSetMailSettingsPanel().getSliderDelayMails().getValue()
                                * viewMain.getSelectRecipientsPanel().getTable().getRowCount()
                                / viewMain.getSetMailSettingsPanel().getSliderAmountMails().getValue()
                        + " Seconds");
    });

    /**
     * Starts the sending of th Mails, when the send button is clicked
     */
    viewMain.getCheckAllSettings().getSendMails().addActionListener(e -> {

        String subject = viewMain.getSetMailSettingsPanel().getFieldSubject().getText();
        Sender sender = (Sender) viewMain.getSetMailSettingsPanel().getSelectSender().getSelectedItem();
        JTable table = viewMain.getSelectRecipientsPanel().getTable();

        if (table != null && sender != null && !subject.equals("")) {
            new sendMails(viewMain);
        }
    });

    /**
     * Clears the Table on buttonclick
     */
    viewMain.getSelectRecipientsPanel().getClearTableButton().addActionListener(e -> {
        viewMain.getSelectRecipientsPanel().getTable().setModel(new DefaultTableModel());
        viewMain.getSelectRecipientsPanel().getTable().setBackground(null);

    });

    /**
     * Removes a single Row on menu click in the editMailPanel
     */
    viewMain.getSelectRecipientsPanel().getDeleteRow().addActionListener(e -> {
        ((DefaultTableModel) viewMain.getSelectRecipientsPanel().getTable().getModel())
                .removeRow(viewMain.getSelectRecipientsPanel().getTable().getSelectedRowCount());
        viewMain.getSelectRecipientsPanel().getTable().setBackground(null);

    });

    /**
     * The Changes the displayed Value when the Time in the Timespinner is getting changed.
     */
    viewMain.getSetMailSettingsPanel().getTimeSpinner().addChangeListener(e -> {
        parseDate.parseDate(viewMain);
        viewMain.getSetMailSettingsPanel().getLabelSendingIn().setText(parseDate.getDays() + " Days, "
                + parseDate.getHours() + " hours and " + parseDate.getMinutes() + " minutes remaining");
        viewMain.getSetMailSettingsPanel().getLabelSendingAt().setText(parseDate.getDate().toString());
        viewMain.getSetMailSettingsPanel().setDate(parseDate.getDate());

    });
    viewMain.getSetMailSettingsPanel().getDatePicker().addActionListener(e -> {
        parseDate.parseDate(viewMain);
        viewMain.getSetMailSettingsPanel().getLabelSendingIn().setText(parseDate.getDays() + " Days, "
                + parseDate.getHours() + " hours and " + parseDate.getMinutes() + " minutes remaining");
        viewMain.getSetMailSettingsPanel().getLabelSendingAt().setText(parseDate.getDate().toString());
        viewMain.getSetMailSettingsPanel().setDate(parseDate.getDate());
    });

    /**
     * Actionevent for the Edit Sender Button
     */
    viewMain.getSetMailSettingsPanel().getButtonEditSender()
            .addActionListener(e -> new controllerEditSender(controllerMain));

    /**
     * Actionevent for the Import Button in the EditMail View
     */
    viewMain.getEditMailPanel().getImportWord().addActionListener(e -> {
        JFileChooser jChooser = new JFileChooser();

        jChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        jChooser.addChoosableFileFilter(new FileNameExtensionFilter("Microsoft Word 97 - 2003 (.doc)", "doc"));
        jChooser.addChoosableFileFilter(new FileNameExtensionFilter("HTML File (.html)", "html"));
        jChooser.setDialogTitle("Select only Word Documents");
        jChooser.showOpenDialog(null);
        File file = jChooser.getSelectedFile();
        if (file != null) {
            parseFilesForImport parseFilesForImport = new parseFilesForImport();

            if (file.getName().endsWith("doc")) {
                String returnedData = parseFilesForImport.parseDOCFile(file);
                viewMain.getEditMailPanel().setEditorText(returnedData);

            } else if (file.getName().endsWith("html")) {
                String content = "";
                try {
                    content = Jsoup.parse(file, "UTF-8").toString();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                viewMain.getEditMailPanel().setEditorText(content);

            } else {
                JOptionPane.showMessageDialog(null, "Please select a Document file.", "Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    });

    /**
     * The Tab Changelistener
     * The first if Statement sets the Labels on the Checkallsettings Panel to the right Values
     */
    viewMain.getTabbedPane().addChangeListener(e -> {
        if (viewMain.getTabbedPane().getSelectedComponent() == viewMain.getCheckAllSettings()) {

            viewMain.getCheckAllSettings().getLabelMailBelow()
                    .setText(viewMain.getEditMailPanel().getEditorText()); //Displays the Mail

            viewMain.getCheckAllSettings().getLabelRecipientsAmount()
                    .setText("" + viewMain.getSelectRecipientsPanel().getTable().getModel().getRowCount()); //Displays the Amount of Recipients

            if (viewMain.getSetMailSettingsPanel().getSelectSender().getSelectedItem() != null) {
                viewMain.getCheckAllSettings().getLabelFromInserted().setText(
                        viewMain.getSetMailSettingsPanel().getSelectSender().getSelectedItem().toString());
            } else {
                viewMain.getCheckAllSettings().getLabelFromInserted().setText("Select a Sender first");
            }

            viewMain.getCheckAllSettings().getLabelSubjectInserted()
                    .setText(viewMain.getSetMailSettingsPanel().getFieldSubject().getText()); //Displays the Subject

            if (viewMain.getSetMailSettingsPanel().getCheckBoxDelayMails().isSelected()) {
                viewMain.getCheckAllSettings().getLabelDelay().setVisible(true);
                viewMain.getCheckAllSettings().getLabelAmount().setVisible(true);
                viewMain.getCheckAllSettings().getLabelTime().setVisible(true);
                viewMain.getCheckAllSettings().getLabelDelayNumber().setVisible(true);
                viewMain.getCheckAllSettings().getLabelAmountNumber().setVisible(true);
                viewMain.getCheckAllSettings().getLabelTimeAmount().setVisible(true);

                viewMain.getCheckAllSettings().getLabelDelayNumber()
                        .setText("" + viewMain.getSetMailSettingsPanel().getSliderDelayMails().getValue()); //The Delay Number
                viewMain.getCheckAllSettings().getLabelAmountNumber()
                        .setText("" + viewMain.getSetMailSettingsPanel().getSliderAmountMails().getValue()); //The Amount of Mail in one package
                viewMain.getCheckAllSettings().getLabelTimeAmount()
                        .setText(""
                                + viewMain.getSetMailSettingsPanel().getSliderDelayMails().getValue()
                                        * viewMain.getSelectRecipientsPanel().getTable().getRowCount()
                                        / viewMain.getSetMailSettingsPanel().getSliderAmountMails().getValue()
                                + " Seconds"); //The Time the Sending needs

            } else {
                viewMain.getCheckAllSettings().getLabelDelay().setVisible(false);
                viewMain.getCheckAllSettings().getLabelAmount().setVisible(false);
                viewMain.getCheckAllSettings().getLabelTime().setVisible(false);
                viewMain.getCheckAllSettings().getLabelDelayNumber().setVisible(false);
                viewMain.getCheckAllSettings().getLabelAmountNumber().setVisible(false);
                viewMain.getCheckAllSettings().getLabelTimeAmount().setVisible(false);
            }

            if (viewMain.getSetMailSettingsPanel().getCheckBoxSendLater().isSelected()) {
                viewMain.getCheckAllSettings().getLabelSendingAt().setVisible(true);
                viewMain.getCheckAllSettings().getLabelSendingWhen().setVisible(true);
                viewMain.getCheckAllSettings().getLabelSendingAt()
                        .setText(viewMain.getSetMailSettingsPanel().getDate().toString());

            } else {
                viewMain.getCheckAllSettings().getLabelSendingAt().setVisible(false);
                viewMain.getCheckAllSettings().getLabelSendingWhen().setVisible(false);
            }

        }
    });

}

From source file:ImageIOTest.java

/**
 * Open a file and load the images./*from  w  w w.  j a va 2  s  . c om*/
 */
public void openFile() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    String[] extensions = ImageIO.getReaderFileSuffixes();
    chooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions));
    int r = chooser.showOpenDialog(this);
    if (r != JFileChooser.APPROVE_OPTION)
        return;
    File f = chooser.getSelectedFile();
    Box box = Box.createVerticalBox();
    try {
        String name = f.getName();
        String suffix = name.substring(name.lastIndexOf('.') + 1);
        Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
        ImageReader reader = iter.next();
        ImageInputStream imageIn = ImageIO.createImageInputStream(f);
        reader.setInput(imageIn);
        int count = reader.getNumImages(true);
        images = new BufferedImage[count];
        for (int i = 0; i < count; i++) {
            images[i] = reader.read(i);
            box.add(new JLabel(new ImageIcon(images[i])));
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, e);
    }
    setContentPane(new JScrollPane(box));
    validate();
}

From source file:com.sec.ose.osi.ui.frm.main.manage.FileBrowser.java

public void actionPerformed(ActionEvent e) {

    JFCFolderExplorer explorer = JFCFolderExplorer.getInstance();
    JFileChooser chooser = explorer.getJFileChooser();
    String sFileLoc = getFileLocation();

    if ((sFileLoc == null) || (sFileLoc.length() == 0)) {
        chooser.setCurrentDirectory(new java.io.File(sDefaultPath));
    } else {/*from  w w  w. j av  a2  s  .c  o m*/
        chooser.setCurrentDirectory(new java.io.File(sFileLoc));
    }

    int result = explorer.showBrowser(frmOwner);
    String path = "";
    if (result == JFileChooser.APPROVE_OPTION) {
        path = chooser.getSelectedFile().getAbsolutePath();
        if (projectInfo != null)
            projectInfo.setSourcePath(path);

        setFileLocation(path);

        if (projectModel != null)
            projectModel.forceRefreshTable();
    }

    if (sFileLoc == null || !sFileLoc.equals(path)) {
        log.debug("}}}}}}BEFORE{{{{{{ project status will change ---> " + projectInfo.getProjectName() + " : "
                + IdentifiedController.getProjectStatus(projectInfo.getProjectName()) + " : "
                + projectInfo.isSourcePathChange());
        projectInfo.setSourcePathChange(true);
        projectInfo.setAnalyzeTarget(true);
        projectModel.setProjectAnalysisStatus(projectInfo.getProjectName(), ProjectAnalysisInfo.STATUS_READY);
        IdentifiedController.setProjectStatus(projectInfo.getProjectName(), AnalysisMonitorThread.STATUS_READY);
        log.debug("}}}}}}AFTER{{{{{{ project status changed ---> " + projectInfo.getProjectName() + " : "
                + IdentifiedController.getProjectStatus(projectInfo.getProjectName()) + " : "
                + projectInfo.isSourcePathChange());
    } else {
        projectInfo.setSourcePathChange(false);
    }
}

From source file:de.dfki.owlsmx.gui.ShowResultVisualization.java

private void saveActionPerformed(java.awt.event.ActionEvent event) {//GEN-FIRST:event_saveActionPerformed
    try {//ww w  . j a  v  a2s . co m
        if (event.getSource().equals(save)) {
            if (fc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                if (fc.getFileFilter().getClass().equals((new PNGFilter()).getClass()))
                    if (fc.getSelectedFile().getAbsolutePath().toLowerCase().endsWith(".png"))
                        ChartUtilities.saveChartAsPNG(fc.getSelectedFile(), chart,
                                ResultVisualization.graphPrintWidth, ResultVisualization.graphPrintHeight);
                    else
                        ChartUtilities.saveChartAsPNG(new File(fc.getSelectedFile().getAbsolutePath() + ".png"),
                                chart, ResultVisualization.graphPrintWidth,
                                ResultVisualization.graphPrintHeight);

                else if (fc.getFileFilter().getClass().equals((new JPGFilter()).getClass()))
                    if (fc.getSelectedFile().getAbsolutePath().toLowerCase().endsWith(".png"))
                        ChartUtilities.saveChartAsJPEG(fc.getSelectedFile(), chart,
                                ResultVisualization.graphPrintWidth, ResultVisualization.graphPrintHeight);
                    else
                        ChartUtilities.saveChartAsJPEG(
                                new File(fc.getSelectedFile().getAbsolutePath() + ".png"), chart,
                                ResultVisualization.graphPrintWidth, ResultVisualization.graphPrintHeight);

                else if (fc.getFileFilter().getClass().equals((new PDFFilter()).getClass()))
                    if (fc.getSelectedFile().getAbsolutePath().toLowerCase().endsWith(".pdf"))
                        Converter.convertToPdf(chart, ResultVisualization.graphPrintWidth,
                                ResultVisualization.graphPrintHeight, fc.getSelectedFile().getAbsolutePath());
                    else
                        Converter.convertToPdf(chart, ResultVisualization.graphPrintWidth,
                                ResultVisualization.graphPrintHeight,
                                fc.getSelectedFile().getAbsolutePath() + ".pdf");
                else if (fc.getFileFilter().getClass().equals((new EPSFilter()).getClass()))
                    printGraphics2DtoEPS(fc.getSelectedFile().getAbsolutePath());
            }
        }
    } catch (Exception e) {
        GUIState.displayWarning(e.getClass().toString(),
                "Couldn't save file " + fc.getSelectedFile().getAbsolutePath());
        e.printStackTrace();
    }
}

From source file:calendarexportplugin.exporter.CalExporter.java

/**
 * Shows a file chooser for calendar Files.
 *
 * @return selected File/*from  ww w. j  a  v a  2 s  .  c o m*/
 * @param programs
 *          programs that are exported
 */
private File chooseFile(Program[] programs) {
    JFileChooser select = new JFileChooser();

    ExtensionFileFilter vCal = new ExtensionFileFilter(mExtension, mExtensionFilter);
    select.addChoosableFileFilter(vCal);
    String ext = "." + mExtension;

    if (mSavePath != null) {
        select.setSelectedFile(new File(mSavePath));
        select.setFileFilter(vCal);
    }

    // check if all programs have same title. if so, use as filename
    String fileName = programs[0].getTitle();
    for (int i = 1; i < programs.length; i++) {
        if (!programs[i].getTitle().equals(fileName)) {
            fileName = "";
        }
    }

    fileName = CalendarToolbox.cleanFilename(fileName);

    if (StringUtils.isNotEmpty(fileName)) {
        if (mSavePath == null) {
            mSavePath = "";
        }
        select.setSelectedFile(new File((new File(mSavePath).getParent()) + File.separator + fileName + ext));
    }

    if (select.showSaveDialog(
            CalendarExportPlugin.getInstance().getBestParentFrame()) == JFileChooser.APPROVE_OPTION) {

        String filename = select.getSelectedFile().getAbsolutePath();

        if (!filename.toLowerCase().endsWith(ext)) {
            if (filename.endsWith(".")) {
                filename = filename.substring(0, filename.length() - 1);
            }
            filename = filename + ext;
        }

        return new File(filename);
    }

    return null;
}

From source file:com.nubits.nubot.launch.toolkit.LaunchUI.java

private String askUser() {
    //Create Options for option dialog
    String path = "";

    // Set cross-platform Java L&F (also called "Metal")
    try {//from  www . j  a v  a  2s . c o  m
        UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());

        final ImageIcon icon = new ImageIcon(local_path + "/" + ICON_PATH);

        //Ask the user to ask for scratch
        Object[] options = { "Import existing JSON option file", "Configure the bot from scratch" };

        int n = JOptionPane.showOptionDialog(new JFrame(), "Chose one of the following options:",
                "NuBot UI Launcher", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, icon, //do not use a custom Icon
                options, //the titles of buttons
                options[0]); //default button title

        if (n == JOptionPane.YES_OPTION) {

            //Prompt user to chose a file.
            JFileChooser fileChooser = createFileChoser();

            int result = fileChooser.showOpenDialog(new JFrame());
            if (result == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                path = selectedFile.getAbsolutePath();
                LOG.info("Option file selected : " + path);
            } else {
                LOG.info("Closing Launch UI utility.");
                System.exit(0);
            }
        }
    } catch (ClassNotFoundException | UnsupportedLookAndFeelException | IllegalAccessException
            | InstantiationException e) {
        LOG.error(e.toString());
    }

    return path;
}

From source file:JuliaSet3.java

public void save() throws IOException {
    // Find a factory object for printing Printable objects to PostScript.
    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
    String format = "application/postscript";
    StreamPrintServiceFactory factory = StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor,
            format)[0];//  ww w .  j ava 2s  . co m

    // Ask the user to select a file and open the selected file
    JFileChooser chooser = new JFileChooser();
    if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION)
        return;
    File f = chooser.getSelectedFile();
    FileOutputStream out = new FileOutputStream(f);

    // Obtain a PrintService that prints to that file
    StreamPrintService service = factory.getPrintService(out);

    // Do the printing with the method below
    printToService(service, null);

    // And close the output file.
    out.close();
}

From source file:components.FileChooserDemo.java

public void actionPerformed(ActionEvent e) {

    //Handle open button action.
    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(FileChooserDemo.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would open the file.
            log.append("Opening: " + file.getName() + "." + newline);
        } else {/*www .j a  va 2s. co m*/
            log.append("Open command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());

        //Handle save button action.
    } else if (e.getSource() == saveButton) {
        int returnVal = fc.showSaveDialog(FileChooserDemo.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would save the file.
            log.append("Saving: " + file.getName() + "." + newline);
        } else {
            log.append("Save command cancelled by user." + newline);
        }
        log.setCaretPosition(log.getDocument().getLength());
    }
}

From source file:TextFileHandler.java

public File openDirectory(String title) {
    File result = null;/*w w  w.java  2s.  co m*/
    JFileChooser chooser = new JFileChooser(new File("."));
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    if (title != null)
        chooser.setDialogTitle(title);
    int retVal = chooser.showOpenDialog(null);
    if (retVal == JFileChooser.APPROVE_OPTION) {
        result = chooser.getSelectedFile();
    }
    return result;
}

From source file:presenter.MainPresenter.java

@Override
public void loadEmissionsequenceFromFile(ActionEvent e) {
    JFileChooser fc = new JFileChooser();

    if (fc.showOpenDialog((Component) e.getSource()) == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        try {//from   w  w w . j ava  2s  .  co m
            this.emissionsequenceModel = new EmissionsequenceModel(
                    new Scanner(file).useDelimiter("\\A").next());
            this.model = null;
            this.displayStatus("File was read successfully!");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}