Example usage for javax.swing JFileChooser showDialog

List of usage examples for javax.swing JFileChooser showDialog

Introduction

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

Prototype

@SuppressWarnings("deprecation")
public int showDialog(Component parent, String approveButtonText) throws HeadlessException 

Source Link

Document

Pops a custom file chooser dialog with a custom approve button.

Usage

From source file:ch.bfh.lca._15h.server.gui.MainWindowServer.java

private void btnSetDatabasePathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSetDatabasePathActionPerformed

    // JFileChooser-Objekt erstellen
    JFileChooser chooser = new JFileChooser();
    // Dialog zum Speichern von Dateien anzeigen
    int resultValue = chooser.showDialog(null, "Bitte whle die SQLLite Datenbank aus");

    if (resultValue == JFileChooser.APPROVE_OPTION) {
        this.txtDatabasePath.setText(chooser.getSelectedFile().getAbsolutePath());
    }//  w ww  . ja  v  a  2 s. c om

}

From source file:dialog.DialogFunctionUser.java

private void btnUploadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUploadActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    int result = fileChooser.showDialog(null, "Upload avatar");
    if (result == JFileChooser.APPROVE_OPTION) {
        mAvatar = fileChooser.getSelectedFile();
        if (!PictureUtil.isPicture(mAvatar)) {
            JOptionPane.showMessageDialog(null, "?y khng phi l nh", "Error",
                    JOptionPane.ERROR_MESSAGE);
            mAvatar = null;/*from  ww w . j  ava2  s .co  m*/
        } else {
            PictureUtil.setPicture(lbAvatar, mAvatar);
        }
    }
}

From source file:ch.bfh.lca._15h.server.gui.MainWindowServer.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

    // JFileChooser-Objekt erstellen
    JFileChooser chooser = new JFileChooser();
    // Dialog zum Speichern von Dateien anzeigen
    int resultValue = chooser.showDialog(null, "Bitte whle die json Datei aus, die Sie importieren mchten");

    if (resultValue == JFileChooser.APPROVE_OPTION) {
        this.txtJsonPath.setText(chooser.getSelectedFile().getAbsolutePath());
        ImportHandler ih = new ImportHandler(this.txtJsonPath.getText(), this.txtDatabasePath.getText());
        ih.importData();/* www .jav a2  s . co  m*/
        JOptionPane.showMessageDialog(new JFrame(), "Import finished", "Information",
                JOptionPane.INFORMATION_MESSAGE);
    }

}

From source file:jmap2gml.ScriptGui.java

/**
 * Formats the window, initializes the JMap2Script object, and sets up all
 * the necessary events.//from   w w w  . j  av a 2  s .c  om
 */
public ScriptGui() {
    setTitle("jmap to gml script converter");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    getContentPane().setLayout(new GridBagLayout());

    this.addWindowListener(new WindowListener() {
        @Override
        public void windowOpened(WindowEvent we) {
        }

        @Override
        public void windowClosing(WindowEvent we) {
            saveConfig();
        }

        @Override
        public void windowClosed(WindowEvent we) {
        }

        @Override
        public void windowIconified(WindowEvent we) {
        }

        @Override
        public void windowDeiconified(WindowEvent we) {
        }

        @Override
        public void windowActivated(WindowEvent we) {
        }

        @Override
        public void windowDeactivated(WindowEvent we) {
        }
    });

    GridBagConstraints c = new GridBagConstraints();

    setResizable(true);
    setIconImage((new ImageIcon("spikeup.png")).getImage());

    jta = new JTextArea(38, 30);

    loadConfig();

    JScrollPane jsp = new JScrollPane(jta);
    jsp.setRowHeaderView(new TextLineNumber(jta));
    jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    jsp.setSize(jsp.getWidth(), 608);

    // menu bar
    JMenuBar menubar = new JMenuBar();

    // file menu
    JMenu file = new JMenu("File");

    // load button
    JMenuItem load = new JMenuItem("Load jmap");
    load.addActionListener(ae -> {
        JFileChooser fileChooser = new JFileChooser(prevDirectory);
        fileChooser.setFileFilter(new FileNameExtensionFilter("jmap file", "jmap", "jmap"));

        int returnValue = fileChooser.showOpenDialog(null);

        if (returnValue == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();

            prevDirectory = selectedFile.getAbsolutePath();

            jm2s = new ScriptFromJmap(selectedFile.getPath(), false);

            jta.setText("");
            jta.append(jm2s.toString());
            jta.setCaretPosition(0);

            writeFile.setEnabled(true);

            drawPanel.setItems(jta.getText().split("\n"));
        }
    });

    // add load to file menu
    file.add(load);

    // button to save script to file
    writeFile = new JMenuItem("Write file");
    writeFile.addActionListener(ae -> {
        if (jm2s != null) {
            PrintWriter out;
            try {
                File f = new File(
                        jm2s.getFileName().substring(0, jm2s.getFileName().lastIndexOf(".jmap")) + ".gml");
                out = new PrintWriter(f);
                out.append(jm2s.toString());
                out.close();
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ScriptGui.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    writeFile.setEnabled(false);

    JMenuItem gmx = new JMenuItem("Export as gmx");
    gmx.addActionListener(ae -> {
        String fn = String.format("%s.room.gmx", prevDirectory);

        JFileChooser fc = new JFileChooser(prevDirectory);
        fc.setSelectedFile(new File(fn));
        fc.setFileFilter(new FileNameExtensionFilter("Game Maker XML", "gmx", "gmx"));
        fc.showDialog(null, "Save");
        File f = fc.getSelectedFile();

        if (f != null) {
            try {
                GMX.itemsToGMX(drawPanel.items, new FileOutputStream(f));
            } catch (FileNotFoundException ex) {
                Logger.getLogger(ScriptGui.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

    // add to file menu
    file.add(writeFile);
    file.add(gmx);

    // add file menu to the menubar
    menubar.add(file);

    // Edit menu

    // display menu
    JMenu display = new JMenu("Display");

    JMenuItem update = new JMenuItem("Update");

    update.addActionListener(ae -> {
        drawPanel.setItems(jta.getText().split("\n"));
    });

    display.add(update);

    JMenuItem gridToggle = new JMenuItem("Toggle Grid");
    gridToggle.addActionListener(ae -> {
        drawPanel.toggleGrid();
    });
    display.add(gridToggle);

    JMenuItem gridOptions = new JMenuItem("Modify Grid");
    gridOptions.addActionListener(ae -> {
        drawPanel.modifyGrid();
    });
    display.add(gridOptions);

    menubar.add(display);

    // sets the menubar
    setJMenuBar(menubar);

    // add the text area to the window
    c.gridx = 0;
    c.gridy = 0;
    add(jsp, c);

    // initialize the preview panel
    drawPanel = new Preview(this);
    JScrollPane scrollPane = new JScrollPane(drawPanel);

    // add preview panel to the window
    c.gridx = 1;
    c.gridwidth = 2;
    add(scrollPane, c);

    pack();
    setMinimumSize(this.getSize());
    setLocationRelativeTo(null);
    setVisible(true);
    drawPanel.setItems(jta.getText().split("\n"));
}

From source file:com.swg.parse.docx.OpenFolderAction.java

@Override
public void actionPerformed(ActionEvent e) {

    JFileChooser fc = new JFileChooser();
    fc.setCurrentDirectory(new File("C:/"));
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    if (selectedFile != null) {
        fc.setSelectedFile(selectedFile);
    }//from   w  w  w.  ja v a2s  .co m

    int returnVal = fc.showDialog(WindowManager.getDefault().getMainWindow(), "Extract Data");

    JFrame jf = new JFrame("Progress Bar");
    Container Jcontent = jf.getContentPane();
    JProgressBar progressBar = new JProgressBar();
    progressBar.setValue(0);
    progressBar.setStringPainted(true);
    Jcontent.add(progressBar, BorderLayout.NORTH);
    jf.setSize(300, 60);
    jf.setVisible(true);

    //we needed a new thread for a functional progress bar on the JFrame
    new Thread(new Runnable() {
        public void run() {

            if (returnVal == JFileChooser.APPROVE_OPTION) {

                File file = fc.getSelectedFile();
                selectedFile = file;

                FileFilter fileFilter = new WildcardFileFilter("*.docx");
                File[] files = selectedFile.listFiles(fileFilter);
                double cnt = 0, cnt2 = 0; //number of how many .docx is in the folder
                for (File f : files) {
                    if (!f.getAbsolutePath().contains("~"))
                        cnt2++;
                }

                for (File f : files) {
                    cnt++;
                    pathToTxtFile = f.getAbsolutePath().replace(".docx", ".txt");
                    TxtFile = new File(pathToTxtFile);

                    //----------------------------------------------------
                    String zipFilePath = "C:\\Users\\fja2\\Desktop\\junk\\Test\\test.zip";
                    String destDirectory = "C:\\Users\\fja2\\Desktop\\junk\\Test " + cnt;
                    UnzipUtility unzipper = new UnzipUtility();
                    try {
                        File zip = new File(zipFilePath);
                        File directory = new File(destDirectory);
                        FileUtils.copyFile(f, zip);
                        unzipper.UnzipUtility(zip, directory);

                        zip.delete();

                        String mediaPath = destDirectory + "/word/media/";
                        File mediaDir = new File(mediaPath);

                        for (File fil : mediaDir.listFiles()) {
                            FileUtils.copyFile(fil, new File("C:\\Users\\PXT1\\Desktop\\test\\Pictures\\"
                                    + f.getName() + "\\" + fil.getName()));
                        }

                        FileUtils.deleteDirectory(directory);

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

                    //if the txt file doesn't exist, it tries to convert whatever 
                    //can be the txt into the actual txt.
                    if (!TxtFile.exists()) {
                        pathToTxtFile = f.getAbsolutePath().replace(".docx", "");
                        TxtFile = new File(pathToTxtFile);
                        pathToTxtFile += ".txt";
                        TxtFile.renameTo(new File(pathToTxtFile));
                        TxtFile = new File(pathToTxtFile);
                    }

                    String content = "";
                    String POIContent = "";

                    try {
                        content = readTxtFile();
                        version = DetermineVersion(content);
                        NewExtract ext = new NewExtract();
                        ext.extract(content, f.getAbsolutePath(), version, (int) cnt);

                    } catch (FileNotFoundException ex) {
                        Exceptions.printStackTrace(ex);
                    } catch (IOException ex) {
                        Exceptions.printStackTrace(ex);
                    } catch (ParseException ex) {
                        Exceptions.printStackTrace(ex);
                    }

                    double tempProg = (cnt / cnt2) * 100;
                    progressBar.setValue((int) tempProg);
                    System.gc();
                }

            } else {
                //do nothing
            }
        }
    }).start();

    System.gc();

}

From source file:ch.bfh.lca._15h.server.gui.MainWindowServer.java

private String getPath() {
    String text = "";
    FileNameExtensionFilter filter = null;
    String path = "";

    if (this.activeModule.equals("table")) {
        filter = new FileNameExtensionFilter("EXCEL File", "xlsx");
        text = "Wo mchten Sie das Excel ersellen?";
    } else {/*w  w  w.  j  a v  a2s.c o  m*/
        filter = new FileNameExtensionFilter("JPEG File", "jpg");
        text = "Wo mchten Sie das Bild ersellen?";
    }

    // JFileChooser-Objekt erstellen
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(filter);
    // Dialog zum Speichern von Dateien anzeigen
    int resultValue = chooser.showDialog(null, text);

    if (resultValue != JFileChooser.ABORT) {
        path = chooser.getSelectedFile().getAbsolutePath();
    }

    return path;

}

From source file:com.ficeto.esp.EspExceptionDecoder.java

private void createAndUpload() {
    if (!PreferencesData.get("target_platform").contentEquals("esp8266")
            && !PreferencesData.get("target_platform").contentEquals("esp32")
            && !PreferencesData.get("target_platform").contentEquals("ESP31B")) {
        System.err.println();/*from w w w .  java2  s .  c o  m*/
        editor.statusError("Not Supported on " + PreferencesData.get("target_platform"));
        return;
    }

    String tc = "esp32";
    if (PreferencesData.get("target_platform").contentEquals("esp8266")) {
        tc = "lx106";
    }

    TargetPlatform platform = BaseNoGui.getTargetPlatform();

    String gccPath = PreferencesData.get("runtime.tools.xtensa-" + tc + "-elf-gcc.path");
    if (gccPath == null) {
        gccPath = platform.getFolder() + "/tools/xtensa-" + tc + "-elf";
    }

    String addr2line;
    if (PreferencesData.get("runtime.os").contentEquals("windows"))
        addr2line = "xtensa-" + tc + "-elf-addr2line.exe";
    else
        addr2line = "xtensa-" + tc + "-elf-addr2line";

    tool = new File(gccPath + "/bin", addr2line);
    if (!tool.exists() || !tool.isFile()) {
        System.err.println();
        editor.statusError("ERROR: " + addr2line + " not found!");
        return;
    }

    elf = new File(getBuildFolderPath(editor.getSketch()), editor.getSketch().getName() + ".ino.elf");
    if (!elf.exists() || !elf.isFile()) {
        elf = new File(getBuildFolderPath(editor.getSketch()), editor.getSketch().getName() + ".cpp.elf");
        if (!elf.exists() || !elf.isFile()) {
            //lets give the user a chance to select the elf
            final JFileChooser fc = new JFileChooser();
            fc.addChoosableFileFilter(new ElfFilter());
            fc.setAcceptAllFileFilterUsed(false);
            int returnVal = fc.showDialog(editor, "Select ELF");
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                elf = fc.getSelectedFile();
            } else {
                editor.statusError("ERROR: elf was not found!");
                System.err.println("Open command cancelled by user.");
                return;
            }
        }
    }

    JFrame.setDefaultLookAndFeelDecorated(true);
    frame = new JFrame("Exception Decoder");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    inputArea = new JTextArea("Paste your stack trace here", 16, 60);
    inputArea.setLineWrap(true);
    inputArea.setWrapStyleWord(true);
    inputArea.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "commit");
    inputArea.getActionMap().put("commit", new CommitAction());
    inputArea.getDocument().addDocumentListener(this);
    frame.getContentPane().add(new JScrollPane(inputArea), BorderLayout.PAGE_START);

    outputText = "";
    outputArea = new JTextPane();
    outputArea.setContentType("text/html");
    outputArea.setEditable(false);
    outputArea.setBackground(null);
    outputArea.setBorder(null);
    outputArea.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, true);
    outputArea.setText(outputText);

    JScrollPane outputScrollPane = new JScrollPane(outputArea);
    outputScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    outputScrollPane.setPreferredSize(new Dimension(640, 200));
    outputScrollPane.setMinimumSize(new Dimension(10, 10));
    frame.getContentPane().add(outputScrollPane, BorderLayout.CENTER);

    frame.pack();
    frame.setVisible(true);
}

From source file:com.swg.parse.docx.OpenWord.java

@Override
public void actionPerformed(ActionEvent e) {

    JFileChooser fc = new JFileChooser();
    fc.setCurrentDirectory(new File("C:/"));
    fc.setAcceptAllFileFilterUsed(false);
    //this authorize only .docx selection
    fc.addChoosableFileFilter(new DocxFileFilter());
    if (selectedFile != null) {
        fc.setSelectedFile(selectedFile);
    }/*from   ww  w . ja  v a 2 s. c  om*/
    int returnVal = fc.showDialog(WindowManager.getDefault().getMainWindow(), "Extract Data");

    if (returnVal == JFileChooser.APPROVE_OPTION) {

        File file = fc.getSelectedFile();
        selectedFile = file;

        pathToTxtFile = selectedFile.getAbsolutePath().replace(".docx", ".txt");
        TxtFile = new File(pathToTxtFile);

        String zipFilePath = "C:\\Users\\KXK3\\Documents\\ZipTest\\test.zip";
        String destDirectory = "C:\\Users\\KXK3\\Documents\\ZipTest\\temp";
        UnzipUtility unzipper = new UnzipUtility();
        try {
            File zip = new File(zipFilePath);
            File directory = new File(destDirectory);
            FileUtils.copyFile(selectedFile, zip);
            unzipper.UnzipUtility(zip, directory);

            String mediaPath = destDirectory + "/word/media/";
            File mediaDir = new File(mediaPath);

            for (File fil : mediaDir.listFiles()) {
                FileUtils.copyFile(fil,
                        new File("C:\\Users\\KXK3\\Documents\\ZipTest\\Pictures\\" + fil.getName()));
            }

            zip.delete();
            FileUtils.deleteDirectory(directory);

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

        //if the txt file doesn't exist, it tries to convert whatever 
        //can be the txt into the actual txt.
        if (!TxtFile.exists()) {
            pathToTxtFile = selectedFile.getAbsolutePath().replace(".docx", "");
            TxtFile = new File(pathToTxtFile);
            pathToTxtFile += ".txt";
            TxtFile.renameTo(new File(pathToTxtFile));
            TxtFile = new File(pathToTxtFile);
        }

        String content;
        String POIContent;

        try {
            content = readTxtFile();
            version = DetermineVersion(content);
            NewExtract ext = new NewExtract();
            ext.extract(content, selectedFile.getAbsolutePath(), version, 1);

        } catch (FileNotFoundException ex) {
            Exceptions.printStackTrace(ex);
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        } catch (ParseException ex) {
            Exceptions.printStackTrace(ex);
        }

    } else {
        //do nothing
    }

}

From source file:net.lldp.checksims.ui.results.ScrollViewer.java

/**
 * Create a scroll viewer from a sortable Matrix Viewer
 * @param results the sortableMatrix to view
 * @param toRevalidate frame to revalidate sometimes
 *///from ww w .  ja v  a2s .  c o  m
public ScrollViewer(SimilarityMatrix exportMatrix, SortableMatrixViewer results, JFrame toRevalidate) {
    resultsView = new JScrollPane(results);
    setBackground(Color.black);
    resultsView.addComponentListener(new ComponentListener() {

        @Override
        public void componentHidden(ComponentEvent arg0) {
        }

        @Override
        public void componentMoved(ComponentEvent arg0) {
        }

        @Override
        public void componentResized(ComponentEvent ce) {
            Dimension size = ce.getComponent().getSize();
            results.padToSize(size);
        }

        @Override
        public void componentShown(ComponentEvent arg0) {
        }
    });

    resultsView.getViewport().addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            Rectangle r = resultsView.getViewport().getViewRect();
            results.setViewAt(r);
        }
    });

    resultsView.setBackground(Color.black);
    sidebar = new JPanel();

    setPreferredSize(new Dimension(900, 631));
    setMinimumSize(new Dimension(900, 631));
    sidebar.setPreferredSize(new Dimension(200, 631));
    sidebar.setMaximumSize(new Dimension(200, 3000));
    resultsView.setMinimumSize(new Dimension(700, 631));
    resultsView.setPreferredSize(new Dimension(700, 631));

    sidebar.setBackground(Color.GRAY);

    setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));

    this.add(sidebar);
    this.add(resultsView);

    resultsView.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    resultsView.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    resultsView.getVerticalScrollBar().setUnitIncrement(16);
    resultsView.getHorizontalScrollBar().setUnitIncrement(16);

    Integer[] presetThresholds = { 80, 60, 40, 20, 0 };
    JComboBox<Integer> threshHold = new JComboBox<Integer>(presetThresholds);
    threshHold.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent event) {
            if (event.getStateChange() == ItemEvent.SELECTED) {
                Integer item = (Integer) event.getItem();
                results.updateThreshold(item / 100.0);
                toRevalidate.revalidate();
                toRevalidate.repaint();
            }
        }
    });
    threshHold.setSelectedIndex(0);
    results.updateThreshold((Integer) threshHold.getSelectedItem() / 100.0);

    JTextField student1 = new JTextField(15);
    JTextField student2 = new JTextField(15);

    KeyListener search = new KeyListener() {

        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
            results.highlightMatching(student1.getText(), student2.getText());
            toRevalidate.revalidate();
            toRevalidate.repaint();
        }

        @Override
        public void keyTyped(KeyEvent e) {
        }
    };

    student1.addKeyListener(search);
    student2.addKeyListener(search);

    Collection<MatrixPrinter> printerNameSet = MatrixPrinterRegistry.getInstance()
            .getSupportedImplementations();
    JComboBox<MatrixPrinter> exportAs = new JComboBox<>(new Vector<>(printerNameSet));
    JButton exportAsSave = new JButton("Save");

    JFileChooser fc = new JFileChooser();

    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.setCurrentDirectory(new java.io.File("."));
    fc.setDialogTitle("Save results");

    exportAsSave.addActionListener(ae -> {
        MatrixPrinter method = (MatrixPrinter) exportAs.getSelectedItem();

        int err = fc.showDialog(toRevalidate, "Save");
        if (err == JFileChooser.APPROVE_OPTION) {
            try {
                FileUtils.writeStringToFile(fc.getSelectedFile(), method.printMatrix(exportMatrix));
            } catch (InternalAlgorithmError | IOException e1) {
                // TODO log / show error
            }
        }
    });

    JPanel thresholdLabel = new JPanel();
    JPanel studentSearchLabel = new JPanel();
    JPanel fileOutputLabel = new JPanel();

    thresholdLabel.setBorder(BorderFactory.createTitledBorder("Matching Threshold"));
    studentSearchLabel.setBorder(BorderFactory.createTitledBorder("Student Search"));
    fileOutputLabel.setBorder(BorderFactory.createTitledBorder("Save Results"));

    thresholdLabel.add(threshHold);
    studentSearchLabel.add(student1);
    studentSearchLabel.add(student2);
    fileOutputLabel.add(exportAs);
    fileOutputLabel.add(exportAsSave);

    studentSearchLabel.setPreferredSize(new Dimension(200, 100));
    studentSearchLabel.setMinimumSize(new Dimension(200, 100));
    thresholdLabel.setPreferredSize(new Dimension(200, 100));
    thresholdLabel.setMinimumSize(new Dimension(200, 100));
    fileOutputLabel.setPreferredSize(new Dimension(200, 100));
    fileOutputLabel.setMinimumSize(new Dimension(200, 100));

    sidebar.setMaximumSize(new Dimension(200, 4000));

    sidebar.add(thresholdLabel);
    sidebar.add(studentSearchLabel);
    sidebar.add(fileOutputLabel);
}

From source file:net.sf.keystore_explorer.gui.dialogs.DViewCertCsrPem.java

private void exportPressed() {
    File chosenFile = null;//from w  w w. j  av a 2  s.c o m
    FileWriter fw = null;

    String title;
    if (cert != null) {
        title = res.getString("DViewCertCsrPem.ExportPemCertificate.Title");
    } else {
        title = res.getString("DViewCertCsrPem.ExportPemCsr.Title");
    }
    try {
        String certPem = jtaPem.getText();

        JFileChooser chooser = FileChooserFactory.getX509FileChooser();
        chooser.setCurrentDirectory(CurrentDirectory.get());
        chooser.setDialogTitle(title);
        chooser.setMultiSelectionEnabled(false);

        int rtnValue = JavaFXFileChooser.isFxAvailable() ? chooser.showSaveDialog(this)
                : chooser.showDialog(this, res.getString("DViewCertCsrPem.ChooseExportFile.button"));

        if (rtnValue != JFileChooser.APPROVE_OPTION) {
            return;
        }

        chosenFile = chooser.getSelectedFile();
        CurrentDirectory.updateForFile(chosenFile);

        if (chosenFile.isFile()) {
            String message = MessageFormat.format(res.getString("DViewCertCsrPem.OverWriteFile.message"),
                    chosenFile);

            int selected = JOptionPane.showConfirmDialog(this, message, title, JOptionPane.YES_NO_OPTION);
            if (selected != JOptionPane.YES_OPTION) {
                return;
            }
        }

        fw = new FileWriter(chosenFile);
        fw.write(certPem);
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(this,
                MessageFormat.format(res.getString("DViewCertCsrPem.NoWriteFile.message"), chosenFile), title,
                JOptionPane.WARNING_MESSAGE);
        return;
    } catch (Exception ex) {
        DError.displayError(this, ex);
        return;
    } finally {
        IOUtils.closeQuietly(fw);
    }

    JOptionPane.showMessageDialog(this, res.getString("DViewCertCsrPem.ExportPemCertificateSuccessful.message"),
            title, JOptionPane.INFORMATION_MESSAGE);
}