Example usage for javax.swing JFileChooser CANCEL_OPTION

List of usage examples for javax.swing JFileChooser CANCEL_OPTION

Introduction

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

Prototype

int CANCEL_OPTION

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

Click Source Link

Document

Return value if cancel is chosen.

Usage

From source file:kenh.xscript.ScriptUtils.java

public static void main(String[] args) {
    String file = null;/*from ww w .  j  ava 2  s  .  c o  m*/

    for (String arg : args) {
        if (StringUtils.startsWithAny(StringUtils.lowerCase(arg), "-f:", "-file:")) {
            file = StringUtils.substringAfter(arg, ":");
        }
    }

    Element e = null;
    try {
        if (StringUtils.isBlank(file)) {

            JFileChooser chooser = new JFileChooser();
            chooser.setDialogTitle("xScript");
            chooser.setAcceptAllFileFilterUsed(false);
            chooser.setFileFilter(new FileFilter() {
                public boolean accept(File f) {
                    if (f.isDirectory()) {
                        return true;
                    } else if (f.isFile() && StringUtils.endsWithIgnoreCase(f.getName(), ".xml")) {
                        return true;
                    }
                    return false;
                }

                public String getDescription() {
                    return "xScript (*.xml)";
                }
            });

            int returnVal = chooser.showOpenDialog(null);
            chooser.requestFocus();

            if (returnVal == JFileChooser.CANCEL_OPTION)
                return;

            File f = chooser.getSelectedFile();

            e = getInstance(f, null);
        } else {
            e = getInstance(new File(file), null);
        }
        //debug(e);
        //System.out.println("----------------------");

        int result = e.invoke();
        if (result == Element.EXCEPTION) {
            Object obj = e.getEnvironment().getVariable(Constant.VARIABLE_EXCEPTION);
            if (obj != null && obj instanceof Throwable) {
                System.err.println();
                ((Throwable) obj).printStackTrace();

            } else {
                System.err.println();
                System.err.println("Unknown EXCEPTION is thrown.");
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();

        System.err.println();

        if (ex instanceof UnsupportedScriptException) {
            UnsupportedScriptException ex_ = (UnsupportedScriptException) ex;
            if (ex_.getElement() != null) {
                debug(ex_.getElement(), System.err);
            }
        }
    } finally {
        if (e != null)
            e.getEnvironment().callback();
    }
}

From source file:Main.java

/**
 * Displays the given file chooser. Utility method for avoiding of memory leak in JDK
 * 1.3 {@link javax.swing.JFileChooser#showDialog}.
 *
 * @param chooser the file chooser to display.
 * @param parent the parent window.//  w  w w .java2  s .  c  om
 * @param approveButtonText the text for the approve button.
 *
 * @return the return code of the chooser.
 */
public static final int showJFileChooser(JFileChooser chooser, Component parent, String approveButtonText) {
    if (approveButtonText != null) {
        chooser.setApproveButtonText(approveButtonText);
        chooser.setDialogType(javax.swing.JFileChooser.CUSTOM_DIALOG);
    }

    Frame frame = (parent instanceof Frame) ? (Frame) parent
            : (Frame) javax.swing.SwingUtilities.getAncestorOfClass(java.awt.Frame.class, parent);
    String title = chooser.getDialogTitle();

    if (title == null) {
        title = chooser.getUI().getDialogTitle(chooser);
    }

    final JDialog dialog = new JDialog(frame, title, true);
    dialog.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

    Container contentPane = dialog.getContentPane();
    contentPane.setLayout(new BorderLayout());
    contentPane.add(chooser, BorderLayout.CENTER);
    dialog.pack();
    dialog.setLocationRelativeTo(parent);
    chooser.rescanCurrentDirectory();

    final int[] retValue = new int[] { javax.swing.JFileChooser.CANCEL_OPTION };

    ActionListener l = new ActionListener() {
        public void actionPerformed(ActionEvent ev) {
            if (ev.getActionCommand() == JFileChooser.APPROVE_SELECTION) {
                retValue[0] = JFileChooser.APPROVE_OPTION;
            }

            dialog.setVisible(false);
            dialog.dispose();
        }
    };

    chooser.addActionListener(l);
    dialog.show();

    return (retValue[0]);
}

From source file:org.pmedv.jake.commands.OpenPlayerViewCommand.java

@Override
public void execute() {

    final ApplicationContext ctx = AppContext.getApplicationContext();
    final ApplicationWindow win = (ApplicationWindow) ctx.getBean(BeanDirectory.WINDOW_APPLICATION);

    /**//  w w w  .j a  v a2s.co m
     * Get last selected folder to simplify file browsing
     */

    if (AppContext.getLastSelectedFolder() == null)
        AppContext.setLastSelectedFolder(System.getProperty("user.home"));

    JFileChooser fc = new JFileChooser(AppContext.getLastSelectedFolder());
    fc.setDialogTitle("Open directory");
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

    int result = fc.showOpenDialog(win);

    if (result == JFileChooser.CANCEL_OPTION)
        return;

    AppContext.setLastSelectedFolder(fc.getSelectedFile().getAbsolutePath());

    List<File> files = new ArrayList<File>();
    FileUtils.findFile(files, fc.getSelectedFile(), ".mp3", true, true);

    final PlayerController controller = new PlayerController(files);
    JakeUtil.updateRecentFiles(fc.getSelectedFile().getAbsolutePath());

    View view = new View(fc.getSelectedFile().getAbsolutePath(), null, controller.getPlayerView());

    view.addListener(new DockingWindowAdapter() {

        @Override
        public void windowClosing(DockingWindow arg0) throws OperationAbortedException {
            if (controller.getPlayer() != null)
                controller.getPlayer().close();
            controller.getPlayFileCommand().setPlaying(false);
        }

    });

    openEditor(view);
}

From source file:org.pmedv.jake.commands.AddFilesCommand.java

@Override
public void execute() {

    final ApplicationContext ctx = AppContext.getApplicationContext();
    final ApplicationWindow win = (ApplicationWindow) ctx.getBean(BeanDirectory.WINDOW_APPLICATION);

    /**//from  w  w w . ja  v a  2s.  com
     * Get last selected folder to simplify file browsing
     */

    if (AppContext.getLastSelectedFolder() == null)
        AppContext.setLastSelectedFolder(System.getProperty("user.home"));

    JFileChooser fc = new JFileChooser(AppContext.getLastSelectedFolder());
    fc.setDialogTitle("Add files");
    fc.setMultiSelectionEnabled(true);
    fc.setFileFilter(new MP3Filter());

    int result = fc.showOpenDialog(win);

    if (result == JFileChooser.CANCEL_OPTION)
        return;

    File[] files = fc.getSelectedFiles();

    PlayerView view = JakeUtil.getCurrentActivePlayer();

    if (view == null) {

        ArrayList<File> fileList = new ArrayList<File>();

        for (int i = 0; i < files.length; i++)
            fileList.add(files[i]);

        final PlayerController controller = new PlayerController(fileList);
        JakeUtil.updateRecentFiles(fc.getSelectedFile().getAbsolutePath());
        AppContext.setLastSelectedFolder(fc.getSelectedFiles()[0].getParentFile().getAbsolutePath());

        View v = new View(fc.getSelectedFile().getAbsolutePath(), null, controller.getPlayerView());

        v.addListener(new DockingWindowAdapter() {

            @Override
            public void windowClosing(DockingWindow arg0) throws OperationAbortedException {

                controller.getPlayer().close();
                controller.getPlayFileCommand().setPlaying(false);
            }

        });

        openEditor(v);
    }

    else {

        if (files.length >= 1) {

            AppContext.setLastSelectedFolder(fc.getSelectedFiles()[0].getParentFile().getAbsolutePath());
            JakeUtil.updateRecentFiles(fc.getSelectedFiles()[0].getParentFile().getAbsolutePath());

            FileTableModel model = (FileTableModel) view.getFileTable().getModel();

            for (int i = 0; i < files.length; i++) {
                model.addObject(files[i]);
            }

        }

    }

}

From source file:SwingUtil.java

/**
 * Open a JFileChooser dialog for selecting a directory and return the
 * selected directory.//from   w w  w.j ava  2s .c  o  m
 *
 *
 * @param owner
 * The frame or dialog that controls the invokation of this dialog.
 * @param defaultDir
 * The directory to show when the dialog opens.
 * @param title
 * Tile for the dialog.
 *
 * @return
 * The selected directory as a File. Null if user cancels dialog without
 * a selection.
 *
 */
public static File getDirectoryChoice(Component owner, File defaultDir, String title) {
    //
    // There is apparently a bug in the native Windows FileSystem class that
    // occurs when you use a file chooser and there is a security manager
    // active. An error dialog is displayed indicating there is no disk in
    // Drive A:. To avoid this, the security manager is temporarily set to
    // null and then reset after the file chooser is closed.
    //
    SecurityManager sm = null;
    JFileChooser chooser = null;
    File choice = null;

    sm = System.getSecurityManager();
    System.setSecurityManager(null);
    chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    if ((defaultDir != null) && defaultDir.exists() && defaultDir.isDirectory()) {
        chooser.setCurrentDirectory(defaultDir);
        chooser.setSelectedFile(defaultDir);
    }
    chooser.setDialogTitle(title);
    chooser.setApproveButtonText("OK");
    int v = chooser.showOpenDialog(owner);

    owner.requestFocus();
    switch (v) {
    case JFileChooser.APPROVE_OPTION:
        if (chooser.getSelectedFile() != null) {
            if (chooser.getSelectedFile().exists()) {
                choice = chooser.getSelectedFile();
            } else {
                File parentFile = new File(chooser.getSelectedFile().getParent());

                choice = parentFile;
            }
        }
        break;
    case JFileChooser.CANCEL_OPTION:
    case JFileChooser.ERROR_OPTION:
    }
    chooser.removeAll();
    chooser = null;
    System.setSecurityManager(sm);
    return choice;
}

From source file:mineria.UI.java

public UI() {
    this.setLayout(new GridBagLayout());

    Label lblnodatos = new Label("NoDatos: ");
    Label label = new Label("BD: ");
    JTextField filename = new JTextField("/Users/eduardomartinez/Documents/mineria/representacion.txt");
    JTextField nodatos = new JTextField();
    nodatos.setText("500");

    JTextField funcion = new JTextField("6");
    JTextField individuos = new JTextField("200");
    JTextField enteros = new JTextField("1");
    JTextField decimales = new JTextField("40");
    JTextField variables = new JTextField("6");
    JTextField Pc = new JTextField("0.9");
    JTextField Pm = new JTextField("0.01");
    JTextField generaciones = new JTextField("100");
    JTextField minimiza = new JTextField("0");

    Label lblfuncion = new Label("funcion: ");
    Label lblindividuos = new Label("individuos: ");
    Label lblenteros = new Label("enteros: ");
    Label lbldecimales = new Label("decimales: ");
    Label lblvariables = new Label("variables: ");
    Label lblpc = new Label("Pc: ");
    Label lblpm = new Label("Pm: ");
    Label lblgeneraciones = new Label("generaciones: ");
    Label lblminimiza = new Label("[0 Min/1 Max] : ");

    /*/*from   w w w  .j  ava  2s  . c  om*/
    FN=funcion;
    N =individuos;
    E =bits_enteros;
    D =bits_decimales;
    V =variables;
    Pc=porcentaje_cruza;
    Pm=porcentaje_muta;
    G =generaciones;
    MM=minimiza;
    */

    JButton openBtn = new JButton("Open BD");
    JButton ejecutarEGA = new JButton("Ejecutar EGA");
    JTextField resultado = new JTextField();
    Label fitness = new Label("fitness: ");

    XYSeriesCollection datosSerie = new XYSeriesCollection();

    AGF agf = new AGF(2);
    EGA ega = new EGA();

    JFreeChart chart = ChartFactory.createScatterPlot("Scatter Plot", // chart title
            "X", // x axis label
            "Y", // y axis label
            datosSerie, // data  ***-----PROBLEM------***
            PlotOrientation.VERTICAL, true, // include legend
            true, // tooltips
            false // urls
    );

    // create and display a frame...
    ChartPanel panelChart = new ChartPanel(chart);

    //leer BD
    openBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            //datosSerie.removeAllSeries();
            if (filename.getText().length() > 0) {
                agf.LeerDatos(filename.getText(), Integer.parseInt(nodatos.getText()));

                createDataset(datosSerie, agf.data, "Datos");
                chart.fireChartChanged();
            } else {
                JFileChooser openFile = new JFileChooser();
                int rVal = openFile.showOpenDialog(null);
                if (rVal == JFileChooser.APPROVE_OPTION) {
                    filename.setText(openFile.getSelectedFile().getAbsolutePath());
                    agf.LeerDatos(filename.getText(), Integer.parseInt(nodatos.getText()));
                    //createDataset(datosSerie, agf.data, "Datos");
                    //chart.fireChartChanged();
                }
                if (rVal == JFileChooser.CANCEL_OPTION) {
                    filename.setText("");
                    //dir.setText("");
                }
            }
        }
    });

    ejecutarEGA.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            //datosSerie.removeAllSeries();
            if (datosSerie.getSeriesCount() > 1)
                datosSerie.removeSeries(1);

            int fn = Integer.parseInt(funcion.getText());
            int n = Integer.parseInt(individuos.getText());
            int e = Integer.parseInt(enteros.getText());
            int d = Integer.parseInt(decimales.getText());
            int v = Integer.parseInt(variables.getText());
            double pc = Double.parseDouble(Pc.getText());
            double pm = Double.parseDouble(Pm.getText());
            int g = Integer.parseInt(generaciones.getText());
            int mm = Integer.parseInt(minimiza.getText());

            ega.setParams(fn, n, e, d, v, pc, pm, g, mm);

            Resultado res = ega.ejecutarAlgoritmoGenetico(agf);

            resultado.setText(String.valueOf(res.getFitnessSemental()));

            res.creaArchivo();
            createDataset(datosSerie, res.getFenotipoSemental(), "Centros");

            Shape cross = ShapeUtilities.createDiagonalCross(5, 1);
            XYPlot xyPlot = (XYPlot) chart.getPlot();
            xyPlot.setDomainCrosshairVisible(true);
            xyPlot.setRangeCrosshairVisible(true);
            XYItemRenderer renderer = xyPlot.getRenderer();
            renderer.setSeriesShape(1, cross);
            renderer.setSeriesPaint(1, Color.blue);

            chart.fireChartChanged();

        }
    });
    //ejecutar AG

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 2;
    gbc.gridy = 0;
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblnodatos, gbc);

    gbc.gridx = 3;
    gbc.gridy = 0;
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(nodatos, gbc);

    gbc.gridx = 2;
    gbc.gridy = 1;
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(filename, gbc);

    gbc.gridx = 3;
    gbc.gridy = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(openBtn, gbc);

    gbc.gridx = 2;
    gbc.gridy = 2;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(fitness, gbc);

    gbc.gridx = 3;
    gbc.gridy = 2;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(resultado, gbc);

    gbc.gridx = 2;
    gbc.gridy = 3;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(ejecutarEGA, gbc);

    //-----------------PARAMETROS
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblfuncion, gbc);

    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(funcion, gbc);

    gbc.gridx = 0;
    gbc.gridy = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblindividuos, gbc);

    gbc.gridx = 1;
    gbc.gridy = 1;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(individuos, gbc);

    gbc.gridx = 0;
    gbc.gridy = 2;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblenteros, gbc);

    gbc.gridx = 1;
    gbc.gridy = 2;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(enteros, gbc);

    gbc.gridx = 0;
    gbc.gridy = 3;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lbldecimales, gbc);

    gbc.gridx = 1;
    gbc.gridy = 3;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(decimales, gbc);

    gbc.gridx = 0;
    gbc.gridy = 4;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblvariables, gbc);

    gbc.gridx = 1;
    gbc.gridy = 4;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(variables, gbc);

    gbc.gridx = 0;
    gbc.gridy = 5;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblpc, gbc);

    gbc.gridx = 1;
    gbc.gridy = 5;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(Pc, gbc);

    gbc.gridx = 0;
    gbc.gridy = 6;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblpm, gbc);

    gbc.gridx = 1;
    gbc.gridy = 6;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(Pm, gbc);

    gbc.gridx = 0;
    gbc.gridy = 7;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblgeneraciones, gbc);

    gbc.gridx = 1;
    gbc.gridy = 7;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(generaciones, gbc);

    gbc.gridx = 0;
    gbc.gridy = 8;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(lblminimiza, gbc);

    gbc.gridx = 1;
    gbc.gridy = 8;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    this.add(minimiza, gbc);

    gbc.fill = GridBagConstraints.BOTH;
    gbc.gridx = 0;
    gbc.gridy = 9;
    gbc.gridheight = 2;
    gbc.gridwidth = 4;
    this.add(panelChart, gbc);

    this.setTitle("File Chooser");

    this.pack();
}

From source file:SwingUtil.java

/**
 * Get a file selection using the FileChooser dialog.
 *
 * @param owner/*  ww w . jav  a2 s .  com*/
 * The parent of this modal dialog.
 * @param defaultSelection
 * The default file selection as a file.
 * @param filter
 * An extension filter
 * @param title
 * The caption for the dialog.
 *
 * @return
 * A selected file or null if no selection is made.
 */
public static File getFileChoice(Component owner, File defaultSelection, FileFilter filter, String title) {
    //
    // There is apparently a bug in the native Windows FileSystem class that
    // occurs when you use a file chooser and there is a security manager
    // active. An error dialog is displayed indicating there is no disk in
    // Drive A:. To avoid this, the security manager is temporarily set to
    // null and then reset after the file chooser is closed.
    //
    SecurityManager sm = null;
    File choice = null;
    JFileChooser chooser = null;

    sm = System.getSecurityManager();
    System.setSecurityManager(null);

    chooser = new JFileChooser();
    if (defaultSelection.isDirectory()) {
        chooser.setCurrentDirectory(defaultSelection);
    } else {
        chooser.setSelectedFile(defaultSelection);
    }
    chooser.setFileFilter(filter);
    chooser.setDialogTitle(title);
    chooser.setApproveButtonText("OK");
    int v = chooser.showOpenDialog(owner);

    owner.requestFocus();
    switch (v) {
    case JFileChooser.APPROVE_OPTION:
        if (chooser.getSelectedFile() != null) {
            choice = chooser.getSelectedFile();
        }
        break;
    case JFileChooser.CANCEL_OPTION:
    case JFileChooser.ERROR_OPTION:
    }
    chooser.removeAll();
    chooser = null;
    System.setSecurityManager(sm);
    return choice;
}

From source file:com.rpgsheet.xcom.PimpMyXcom.java

private static void openXcomPathDialog(Properties appProperties) {
    // display the box to the user
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("PimpMyXcom - Where is X-COM?");
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int retCode = fileChooser.showOpenDialog(null);
    // if the user cancelled the dialog, there is nothing we can do
    if (retCode == JFileChooser.CANCEL_OPTION) {
        log.error("User cancel while attempting to locate X-COM.");
        return;//from   w  w w.ja  v  a 2 s. c o m
    }
    // if there was an error, there is nothing we can do
    if (retCode == JFileChooser.ERROR_OPTION) {
        log.error("Error while attempting to locate X-COM: {}", JFileChooser.ERROR_OPTION);
        return;
    }
    // if the user chose a directory, then we have some work to do
    String xcomPath = fileChooser.getSelectedFile().getAbsolutePath();
    File xcomDir = new File(xcomPath);
    if (containsXcom(xcomDir)) {
        // store the path to xcom in the application properties
        appProperties.setProperty("xcom.path", xcomPath);
        // write the updated application properties to disk
        try {
            saveApplicationProperties(appProperties);
        } catch (IOException e) {
            log.error("Unable to store X-COM path in application properties.", e);
            return;
        }
    }
    // if we were unable to find X-COM
    else {
        log.error("User provided location did not contain X-COM.");
        return;
    }
}

From source file:edu.gcsc.vrl.jfreechart.JFExport.java

/**
 * Show dialog for exporting JFreechart object.
 *//*from  w  ww  .  j a  v  a  2s.c o m*/
public void openExportDialog(JFreeChart jfreechart) {

    JFileChooser chooser = new JFileChooser();
    String path0;
    File file;

    chooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF Files", "pdf"));
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("JPEG Files", "jpg"));
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("PNG Files", "png"));
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("EPS Files", "eps"));
    chooser.addChoosableFileFilter(new FileNameExtensionFilter("SVG Files", "svg"));

    chooser.setFileFilter(new FileNameExtensionFilter("PDF Files", "pdf"));

    int returnVal = chooser.showSaveDialog(null);
    String fd = chooser.getFileFilter().getDescription();

    // Get selected FileFilter 
    String filter_extension = null;
    if (fd.equals("PNG Files")) {
        filter_extension = "png";
    }
    if (fd.equals("SVG Files")) {
        filter_extension = "svg";
    }
    if (fd.equals("JPEG Files")) {
        filter_extension = "jpg";
    }
    if (fd.equals("PDF Files")) {
        filter_extension = "pdf";
    }
    if (fd.equals("EPS Files")) {
        filter_extension = "eps";
    }

    // Cancel
    if (returnVal == JFileChooser.CANCEL_OPTION) {
        return;
    }

    // OK
    if (returnVal == JFileChooser.APPROVE_OPTION) {

        path0 = chooser.getSelectedFile().getAbsolutePath();
        //System.out.println(path0);
        try {
            file = new File(path0);
            // Get extension (if any)
            String ext = JFUtils.getExtension(file);
            // No extension -> use selected Filter
            if (ext == null) {
                file = new File(path0 + "." + filter_extension);
                ext = filter_extension;
            }

            // File exists - overwrite ?
            if (file.exists()) {
                Object[] options = { "OK", "CANCEL" };
                int answer = JOptionPane.showOptionDialog(null, "File exists - Overwrite ?", "Warning",
                        JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]);
                if (answer != JOptionPane.YES_OPTION) {
                    return;
                }
                //System.out.println(answer+"");
            }

            // Export file
            export(file, jfreechart);
        } catch (Exception f) {
            // I/O - Error
        }
    }
}

From source file:edu.harvard.i2b2.adminTool.dataModel.PatientIDConversionFactory.java

private String getKey() {
    String path = null;/*from w  w w .  ja v  a 2  s .  c  o  m*/
    String key = UserInfoBean.getInstance().getKey();
    if (key == null) {
        if ((path = getNoteKeyDrive()) == null) {
            Object[] possibleValues = { "Type in the key", "Browse to find the file containing the key" };
            String selectedValue = (String) JOptionPane.showInputDialog(null,
                    "You have selected an item associated with a report\n"
                            + "which contains protected health information.\n"
                            + "You need a decryption key to perform this operation.\n"
                            + "How would you like to enter the key?\n"
                            + "(If the key is on a floppy disk, insert the disk then\n select "
                            + "\"Browse to find the file containing the key\")",
                    "Notes Viewer", JOptionPane.QUESTION_MESSAGE, null, possibleValues, possibleValues[0]);
            if (selectedValue == null) {
                return "Not a valid key";
            }
            if (selectedValue.equalsIgnoreCase("Type in the key")) {
                key = JOptionPane.showInputDialog(this, "Please input the decryption key");
                if (key == null) {
                    return "Not a valid key";
                }
            } else {
                JFileChooser chooser = new JFileChooser();
                int returnVal = chooser.showOpenDialog(null);
                if (returnVal == JFileChooser.CANCEL_OPTION) {
                    return "Not a valid key";
                }

                File f = null;
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    f = chooser.getSelectedFile();
                    System.out.println("Open this file: " + f.getAbsolutePath());

                    BufferedReader in = null;
                    try {
                        in = new BufferedReader(new FileReader(f.getAbsolutePath()));
                        String line = null;
                        while ((line = in.readLine()) != null) {
                            if (line.length() > 0) {
                                key = line.substring(line.indexOf("\"") + 1, line.lastIndexOf("\""));
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (in != null) {
                            try {
                                in.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        } else {
            System.out.println("Found key file: " + path);
            BufferedReader in = null;
            try {
                in = new BufferedReader(new FileReader(path));
                String line = null;
                while ((line = in.readLine()) != null) {
                    if (line.length() > 0) {
                        key = line.substring(line.indexOf("\"") + 1, line.lastIndexOf("\""));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    if (key == null) {
        return null;
    } else {
        UserInfoBean.getInstance().setKey(key);
    }
    return key;
}