Example usage for javax.swing JFileChooser showSaveDialog

List of usage examples for javax.swing JFileChooser showSaveDialog

Introduction

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

Prototype

public int showSaveDialog(Component parent) throws HeadlessException 

Source Link

Document

Pops up a "Save File" file chooser dialog.

Usage

From source file:table.FrequencyTablePanel.java

public String doSaveAs(File f) throws IOException {
    JFileChooser fileChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF Files", "pdf");
    fileChooser.addChoosableFileFilter(filter);
    fileChooser.setFileFilter(filter);//w  ww .  java  2 s  . c  om
    String filename = "";
    int option = fileChooser.showSaveDialog(this);
    if (option == JFileChooser.APPROVE_OPTION) {
        filename = fileChooser.getSelectedFile().getPath();
        if (!filename.endsWith(".png")) {
            filename = filename + ".png";
        }
        saveTableAsPNG(new File(filename), this.table, getWidth(), getHeight());
    }
    return filename;
}

From source file:com.itemanalysis.jmetrik.swing.GraphPanel.java

public void addJpgMenuItem(final Component parent, JPopupMenu popMenu) {
    JMenuItem mItem = new JMenuItem("Save as JPG...");
    mItem.addActionListener(new ActionListener() {
        @Override/*from   w  ww .java 2 s  .c  o  m*/
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            FileFilter filter1 = new SimpleFilter("jpg", "JPG File (*.jpg)");
            chooser.addChoosableFileFilter(filter1);
            int status = chooser.showSaveDialog(parent);
            if (status == JFileChooser.APPROVE_OPTION) {
                File f = chooser.getSelectedFile();
                try {
                    String fileName = f.getAbsolutePath().toLowerCase();
                    if (!fileName.endsWith("jpg"))
                        fileName += ".jpg";
                    saveAsJPEG(new File(fileName));
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(parent, "IOException: Could not save file", "IOException",
                            JOptionPane.ERROR_MESSAGE);
                }

            }

        }
    });
    popMenu.add(mItem);
}

From source file:de.tntinteractive.portalsammler.gui.DocumentTable.java

private boolean exportDocument(final JFileChooser chooser, final int row) {
    try {//  w ww.  j ava 2  s.com
        final DocumentInfo di = this.getDocumentInRow(row);
        final byte[] content = this.store.getDocument(di);

        chooser.setSelectedFile(new File(this.makeFilenameFor(di)));
        final int result = chooser.showSaveDialog(this.table);
        if (result != JFileChooser.APPROVE_OPTION) {
            return true;
        }

        FileUtils.writeByteArrayToFile(chooser.getSelectedFile(), content);
        this.store.markAsRead(di);
        this.store.writeMetadata();
    } catch (final GeneralSecurityException e) {
        this.gui.showError(e);
    } catch (final IOException e) {
        this.gui.showError(e);
    }
    return false;
}

From source file:eu.apenet.dpt.standalone.gui.dateconversion.DateConversionRulesDialog.java

private void createDataConversionRulesList() {
    Vector<String> columnNames = new Vector<String>();
    columnNames.add(labels.getString("dateConversion.valueRead"));
    columnNames.add(labels.getString("dateConversion.valueConverted"));
    dm = new DefaultTableModel(xmlFilehandler.loadDataFromFile(FILENAME), columnNames);
    dm.addRow(new Vector<String>());
    dm.addTableModelListener(new TableModelListener() {
        public void tableChanged(TableModelEvent e) {
            if (ruleTable.getEditingRow() != ruleTable.getRowCount() - 1
                    && (StringUtils.isEmpty((String) dm.getValueAt(ruleTable.getEditingRow(), 0))
                            && StringUtils.isEmpty((String) dm.getValueAt(ruleTable.getEditingRow(), 1)))) {
                dm.removeRow(ruleTable.getEditingRow());
            }/*from ww  w . j  a  v  a2 s. com*/
            if (ruleTable.getEditingRow() == ruleTable.getRowCount() - 1) {
                if (StringUtils.isNotEmpty((String) dm.getValueAt(ruleTable.getEditingRow(), 0))
                        && StringUtils.isNotEmpty((String) dm.getValueAt(ruleTable.getEditingRow(), 1))) {
                    dm.addRow(new Vector<String>());
                }
            }
            if (ruleTable.getEditingColumn() == 1) {
                if (StringUtils.isNotEmpty((String) dm.getValueAt(ruleTable.getEditingRow(), 1))
                        && !isCorrectDateFormat((String) dm.getValueAt(ruleTable.getEditingRow(), 1))) {
                    createOptionPaneForIsoDate(ruleTable.getEditingRow(), 1);
                }
            }
        }
    });

    ruleTable = new JTable(dm);
    oldModel = new DefaultTableModel(xmlFilehandler.loadDataFromFile(FILENAME), columnNames);

    JButton saveButton = new JButton(labels.getString("saveBtn"));
    saveButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (ruleTable.isEditing()) {
                ruleTable.getCellEditor().stopCellEditing();
            }
            Vector<Vector<String>> data = ((DefaultTableModel) ruleTable.getModel()).getDataVector();
            for (int i = 0; i < data.size() - 1; i++) {
                Vector<String> vector = data.elementAt(i);
                if (vector.elementAt(1) != null && !isCorrectDateFormat((String) vector.elementAt(1))) {
                    createOptionPaneForIsoDate(i, 1);
                }
            }
            xmlFilehandler.saveDataToFile(data, FILENAME);
            saveMessage.setText(MessageFormat.format(labels.getString("dateConversion.saveMsg"),
                    new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime())));
        }
    });

    JButton closeButton = new JButton(labels.getString("quit"));
    closeButton.addActionListener(new ActionListener() {
        // boolean cancel = true;

        public void actionPerformed(ActionEvent e) {
            /*System.out.println(Boolean.toString(oldModel.getRowCount() == (ruleTable.getModel().getRowCount() - 1)) + "<<" + oldModel.getRowCount() + ", " + (ruleTable.getModel().getRowCount() - 1));
            if (oldModel.getRowCount() != ruleTable.getModel().getRowCount() - 1) {
            cancel = showUnsavedChangesDialog();
            } else {
            for (int i = 0; i < (ruleTable.getModel().getRowCount() - 1); i++) {
                for (int j = 0; j <= 1; j++) {
                    System.out.println(oldModel.getValueAt(i, j) == ruleTable.getModel().getValueAt(i, j) + " >> " + oldModel.getValueAt(i, j) + ", " + ruleTable.getModel().getValueAt(i, j));
                    if (oldModel.getValueAt(i, j) != ruleTable.getModel().getValueAt(i, j)) {
                        cancel = showUnsavedChangesDialog();
                    }
                }
            }
            }
            if (cancel) {*/
            dispose();
            //  }
        }
    });

    JButton downloadButton = new JButton(labels.getString("downloadBtn"));
    downloadButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (ruleTable.isEditing()) {
                ruleTable.getCellEditor().stopCellEditing();
            }
            Vector<Vector<String>> data = ((DefaultTableModel) ruleTable.getModel()).getDataVector();
            File currentLocation = new File(retrieveFromDb.retrieveOpenLocation());
            JFileChooser fileChooser = new JFileChooser(currentLocation);
            fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
            fileChooser.setFileFilter(new FileNameExtensionFilter("XML file", "xml"));
            int returnedVal = fileChooser.showSaveDialog(getParent());

            if (returnedVal == JFileChooser.APPROVE_OPTION) {
                String fileName = fileChooser.getSelectedFile().toString();
                if (!fileName.endsWith(".xml")) {
                    fileName = fileName + ".xml";
                }
                xmlFilehandler.saveDataToFile(data, fileName);
                //additionally save data to standard file
                xmlFilehandler.saveDataToFile(data, FILENAME);
                saveMessage.setText(MessageFormat.format(labels.getString("dateConversion.saveMsg"),
                        new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime())));
            }
        }
    });

    JPanel contentPanel = new JPanel(new BorderLayout());
    contentPanel.add(new JScrollPane(ruleTable));
    saveMessage = new JLabel();
    contentPanel.add(saveMessage, BorderLayout.SOUTH);

    JPanel buttonPanel = new JPanel(new GridLayout(1, 3));
    buttonPanel.add(saveButton);
    buttonPanel.add(closeButton);
    buttonPanel.add(downloadButton);

    JPanel pane = new JPanel(new BorderLayout());
    pane.add(contentPanel, BorderLayout.PAGE_START);
    pane.add(buttonPanel, BorderLayout.PAGE_END);
    add(pane);
}

From source file:InterfaceModule.JRobert.java

private void exportToFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportToFileActionPerformed
    JFileChooser chooser = new JFileChooser(System.getProperty("user.dir") + "/saves/");
    chooser.setDialogTitle("Salve o relatrio");
    File fileToSave;/*from w  w  w  . j  a  va2  s  .c o m*/
    int selection = chooser.showSaveDialog(this);
    if (selection == JFileChooser.APPROVE_OPTION)
        fileToSave = chooser.getSelectedFile();
    else
        return;

    try {
        FileWriter fr = new FileWriter(fileToSave);
        BufferedWriter bw = new BufferedWriter(fr);
        String[] text = jTextArea1.getText().split("\n");

        for (String s : text) {
            bw.write(s);
            bw.newLine();
        }
        bw.close();
        fr.close();
    } catch (IOException e) {

    }
}

From source file:electroStaticUI.ElectroStaticUIContainer.java

private void buildFileMenu() {
    //create Exit menu item
    exitItem = new JMenuItem("Exit");
    exitItem.setMnemonic(KeyEvent.VK_X);
    exitItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.exit(0);/*from   w  ww  . jav  a2s .c o m*/
        }
    });

    //open
    open = new JMenuItem("Open");
    open.setMnemonic(KeyEvent.VK_P);
    open.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fChooser = new JFileChooser();
            int status = fChooser.showSaveDialog(null);
        }
    });

    //close
    close = new JMenuItem("Close");
    close.setMnemonic(KeyEvent.VK_C);

    //export
    export = new JMenuItem("Export");
    export.setMnemonic(KeyEvent.VK_E);
    export.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fChooser = new JFileChooser();
            fChooser.setMultiSelectionEnabled(false);
            fChooser.setAcceptAllFileFilterUsed(false);
            FileNameExtensionFilter svgFilter = new FileNameExtensionFilter("Save Vector Plot(svg)", ".svg");
            FileNameExtensionFilter pngFilter = new FileNameExtensionFilter("Save Voltage Surface Plot(png)",
                    ".png");
            fChooser.addChoosableFileFilter(svgFilter);
            fChooser.addChoosableFileFilter(pngFilter);
            fChooser.setFileFilter(svgFilter);
            int status = fChooser.showSaveDialog(rootPane);
            if (status == JFileChooser.APPROVE_OPTION) {
                if (fChooser.getFileFilter() == svgFilter) {
                    try {
                        saveAsName = fChooser.getSelectedFile().getCanonicalPath();
                        Save.saveChartToSVG(DefaultValues.getChartToSave(), saveAsName, displayPanel.getWidth(),
                                displayPanel.getHeight());
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                } else if (fChooser.getFileFilter() == pngFilter) {
                    try {
                        saveAsName = fChooser.getSelectedFile().getCanonicalPath();
                        Save.saveChart3dToPNG(DefaultValues.get3dChartToSave(), saveAsName);
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                }
            }
        }
    });

    //save
    save = new JMenuItem("Save");
    save.setMnemonic(KeyEvent.VK_S);
    save.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fChooser = new JFileChooser();
            int status = fChooser.showSaveDialog(null);
            if (status == JFileChooser.APPROVE_OPTION) {
                try {
                    System.out.println("Height: " + displayPanel.getWidth());
                    System.out.println("Width: " + displayPanel.getHeight());
                    saveAsName = fChooser.getSelectedFile().getCanonicalPath();
                    Save.saveChartToSVG(DefaultValues.getChartToSave(), saveAsName, displayPanel.getWidth(),
                            displayPanel.getHeight());
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }

        }
    });

    //saveAs
    saveAs = new JMenuItem("Save As");
    saveAs.setMnemonic(KeyEvent.VK_A);
    saveAs.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fChooser = new JFileChooser();
            int status = fChooser.showSaveDialog(null);
            if (status == JFileChooser.APPROVE_OPTION)
                try {
                    System.out.println("Height: " + displayPanel.getWidth());
                    System.out.println("Width: " + displayPanel.getHeight());
                    saveAsName = fChooser.getSelectedFile().getCanonicalPath();
                    System.out.println(saveAsName);
                    Save.saveChartToSVG(DefaultValues.getChartToSave(), saveAsName, displayPanel.getWidth(),
                            displayPanel.getHeight());
                } catch (IOException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }
            try {
                Save.saveChartToSVG(UserInput.getElectricFieldChart(), saveAsName, displayPanel.getWidth(),
                        displayPanel.getHeight());
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }
    });

    //JMenu object for file menu
    fileMenu = new JMenu("File");
    fileMenu.setMnemonic(KeyEvent.VK_F);

    //fileMenu.add(newFile);
    //fileMenu.add(open);
    //fileMenu.add(close);
    fileMenu.add(export);
    //fileMenu.add(save);
    //fileMenu.add(saveAs);
    fileMenu.add(exitItem);
}

From source file:marytts.tools.voiceimport.DatabaseImportMain.java

protected void askIfSave() throws IOException {
    if (bnl.hasChanged()) {
        int answer = JOptionPane.showOptionDialog(this, "Do you want to save the list of basenames?", "Save?",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);
        if (answer == JOptionPane.YES_OPTION) {
            JFileChooser fc = new JFileChooser();
            fc.setSelectedFile(new File(db.getProp(db.BASENAMEFILE)));
            int returnVal = fc.showSaveDialog(this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                bnl.write(fc.getSelectedFile());
            }//w  ww . j av a2 s.  c o  m
        }
    } else {
        System.exit(0);
    }
}

From source file:carolina.pegaLatLong.LatLong.java

private void geraCsv(List<InformacaoGerada> gerados) throws IOException {
    JFileChooser escolha = new JFileChooser();
    escolha.setAcceptAllFileFilterUsed(false);
    escolha.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int i = escolha.showSaveDialog(null);
    if (i != 1) {
        System.err.println(escolha.getSelectedFile().getPath() + "\\teste.txt");
        String caminho = escolha.getSelectedFile().getPath();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(caminho + "\\teste.csv"), StandardCharsets.ISO_8859_1));
        //FileWriter arquivo = new FileWriter(caminho + "\\teste.csv");
        //PrintWriter writer = new PrintWriter(arquivo);
        writer.write("Endereco;Latitude;Longitude");
        writer.newLine();// w w  w.  jav a2 s  . co m

        gerados.stream().forEach((gerado) -> {
            try {
                System.err.println(gerado.getEnderecoFormatado() + ";" + gerado.getLatitude() + ";"
                        + gerado.getLongitude() + "\n");
                writer.write(gerado.getEnderecoFormatado() + ";" + gerado.getLatitude() + ";"
                        + gerado.getLongitude());
                writer.newLine();
            } catch (IOException ex) {
                System.err.println("Erro");
            }
        });

        writer.close();
        JOptionPane.showMessageDialog(null, "Finalizado!");

    }

}

From source file:be.fedict.eid.tsl.tool.TslInternalFrame.java

@Override
public void actionPerformed(ActionEvent event) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Save Signer Certificate");
    int result = fileChooser.showSaveDialog(this);
    if (JFileChooser.APPROVE_OPTION == result) {
        File file = fileChooser.getSelectedFile();
        if (file.exists()) {
            int confirmResult = JOptionPane.showConfirmDialog(this,
                    "File already exists.\n" + file.getAbsolutePath() + "\n" + "Overwrite file?", "Overwrite",
                    JOptionPane.OK_CANCEL_OPTION);
            if (JOptionPane.CANCEL_OPTION == confirmResult) {
                return;
            }/* w  w w .j  a v a2  s. c o m*/
        }
        try {
            FileUtils.writeByteArrayToFile(file, this.signerCertificate.getEncoded());
        } catch (Exception e) {
            throw new RuntimeException("error writing file: " + e.getMessage(), e);
        }
    }
}

From source file:colectordedatos.resultados.java

private void Exportar_a_ExcelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Exportar_a_ExcelActionPerformed
    if (jTable1.getRowCount() > 0) {
        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivos de excel", "xls");
        chooser.setFileFilter(filter);/*  w  w  w.  j  a v  a 2  s. co m*/
        chooser.setDialogTitle("Guardar archivo");
        chooser.setAcceptAllFileFilterUsed(false);
        if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
            List<JTable> tb = new ArrayList<JTable>();
            List<String> nom = new ArrayList<String>();
            tb.add(jTable1);
            nom.add("Reporte de Errores");
            String file = chooser.getSelectedFile().toString().concat(".xls");
            try {
                exportaraexcel e = new exportaraexcel(new File(file), tb, nom);
                if (e.export()) {
                    JOptionPane.showMessageDialog(null,
                            "Los datos fueron exportados a excel en el directorio seleccionado",
                            "Mensaje de Informacion", JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Hubo un error " + e.getMessage(), " Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    } else {
        JOptionPane.showMessageDialog(this, "No hay datos para exportar", "Mensaje de error",
                JOptionPane.ERROR_MESSAGE);
    }
}