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:es.emergya.ui.gis.popups.SaveGPXDialog.java

private SaveGPXDialog(final List<Layer> capas) {
    super("Consulta de Posiciones GPS");
    setResizable(false);//from   w  ww .  ja v a2  s. c  o m
    setAlwaysOnTop(true);
    try {
        setIconImage(((BasicWindow) GoClassLoader.getGoClassLoader().load(BasicWindow.class)).getFrame()
                .getIconImage());
    } catch (Throwable e) {
        LOG.error("There is no icon image", e);
    }

    this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    JPanel dialogo = new JPanel(new BorderLayout());
    dialogo.setBackground(Color.WHITE);
    dialogo.setBorder(new EmptyBorder(10, 10, 10, 10));

    JPanel central = new JPanel(new FlowLayout());
    central.setOpaque(false);
    final JTextField nombre = new JTextField(15);
    nombre.setEditable(false);
    central.add(nombre);
    final JButton button = new JButton("Examinar...", LogicConstants.getIcon("button_nuevo"));
    central.add(button);
    final JButton aceptar = new JButton("Guardar", LogicConstants.getIcon("button_save"));
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            if (fileChooser.showSaveDialog(SaveGPXDialog.this) == JFileChooser.APPROVE_OPTION) {
                nombre.setText(fileChooser.getSelectedFile().getAbsolutePath());
                aceptar.setEnabled(true);
            }
        }
    });

    dialogo.add(central, BorderLayout.CENTER);

    JPanel botones = new JPanel(new FlowLayout());
    botones.setOpaque(false);

    aceptar.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String base_url = nombre.getText() + "_";
            for (Layer layer : capas) {
                if (layer instanceof GpxLayer) {
                    GpxLayer gpxLayer = (GpxLayer) layer;
                    File f = new File(base_url + gpxLayer.name + ".gpx");

                    boolean sobreescribir = !f.exists();

                    try {
                        while (!sobreescribir) {
                            String original = f.getCanonicalPath();
                            f = checkFileOverwritten(nombre, f);
                            sobreescribir = !f.exists() || original.equals(f.getCanonicalPath());
                        }
                    } catch (NullPointerException t) {
                        log.debug("Cancelando creacion de fichero: " + t);
                        sobreescribir = false;
                    } catch (Throwable t) {
                        log.error("Error comprobando la sobreescritura", t);
                        sobreescribir = false;
                    }

                    if (sobreescribir) {
                        try {
                            f.createNewFile();
                        } catch (IOException e1) {
                            log.error(e1, e1);
                        }
                        if (!(f.isFile() && f.canWrite()))
                            JOptionPane.showMessageDialog(SaveGPXDialog.this,
                                    "No tengo permiso para escribir en " + f.getAbsolutePath());
                        else {
                            try {
                                OutputStream out = new FileOutputStream(f);
                                GpxWriter writer = new GpxWriter(out);
                                writer.write(gpxLayer.data);
                                out.close();
                            } catch (Throwable t) {
                                log.error("Error al escribir el gpx", t);
                                JOptionPane.showMessageDialog(SaveGPXDialog.this,
                                        "Ocurri un error al escribir en " + f.getAbsolutePath());
                            }
                        }
                    } else
                        log.error("Por errores anteriores no se escribio el fichero");
                } else
                    log.error("Una de las capas no era gpx: " + layer.name);
            }
            SaveGPXDialog.this.dispose();

        }

        private File checkFileOverwritten(final JTextField nombre, File f) throws Exception {
            String nueva = JOptionPane.showInputDialog(nombre, i18n.getString("savegpxdialog.overwrite"),
                    "Sobreescribir archivo", JOptionPane.QUESTION_MESSAGE, null, null, f.getCanonicalPath())
                    .toString();
            log.debug("Nueva ruta: " + nueva);
            return new File(nueva);
        }
    });

    JButton cancelar = new JButton("Cancelar", LogicConstants.getIcon("button_cancel"));

    cancelar.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            SaveGPXDialog.this.dispose();
        }
    });

    aceptar.setEnabled(false);
    botones.add(aceptar);
    botones.add(cancelar);
    dialogo.add(botones, BorderLayout.SOUTH);

    add(dialogo);
    setPreferredSize(new Dimension(300, 200));
    pack();

    int x;
    int y;

    Container myParent;
    try {
        myParent = ((BasicWindow) GoClassLoader.getGoClassLoader().load(BasicWindow.class)).getFrame()
                .getContentPane();
        java.awt.Point topLeft = myParent.getLocationOnScreen();
        Dimension parentSize = myParent.getSize();

        Dimension mySize = getSize();

        if (parentSize.width > mySize.width)
            x = ((parentSize.width - mySize.width) / 2) + topLeft.x;
        else
            x = topLeft.x;

        if (parentSize.height > mySize.height)
            y = ((parentSize.height - mySize.height) / 2) + topLeft.y;
        else
            y = topLeft.y;

        setLocation(x, y);
    } catch (Throwable e1) {
        LOG.error("There is no basic window!", e1);
    }

    this.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosed(WindowEvent e) {
            nombre.setText("");
            nombre.repaint();
        }

        @Override
        public void windowClosing(WindowEvent e) {
            nombre.setText("");
            nombre.repaint();
        }
    });
}

From source file:ch.zhaw.ias.dito.ui.AnalysisPanel.java

@Override
public void actionPerformed(ActionEvent e) {
    JFileChooser fileChooser = new JFileChooser();
    Integer dimensions = (Integer) dimensionsCombo.getSelectedItem();
    double[][] mdsValues = decomp.getReducedDimensions(dimensions);
    int returnVal = fileChooser.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        Matrix m = Matrix.createDoubleMatrix(mdsValues);
        try {//from  w ww.  j  a v  a  2 s.co  m
            Matrix.writeToFile(m, file.getAbsolutePath(), ';', 5);
        } catch (IOException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }
    }
}

From source file:de.mpg.mpi_inf.bioinf.netanalyzer.ui.ChartDisplayPanel.java

/**
 * Displays a dialog for saving the complex parameter data into a text file.
 * <p>/*w  ww.  ja va  2 s. c o  m*/
 * If the user presses the &quot;Save&quot; button of the shown dialog, the complex parameter is
 * saved to the chosen file.
 * </p>
 */
private void saveChartData() {
    JFileChooser saveFileDialog = new JFileChooser();
    int saveIt = saveFileDialog.showSaveDialog(this);
    if (saveIt == JFileChooser.APPROVE_OPTION) {
        FileWriter writer = null;
        try {
            File file = saveFileDialog.getSelectedFile();
            if (Utils.canSave(file, this)) {
                writer = new FileWriter(file);
                visualizer.getComplexParam().save(writer, false);
            }
        } catch (IOException ex) {
            Utils.showErrorBox(this, Messages.DT_IOERROR, Messages.SM_OERROR);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException ex) {
                    // Fall through
                }
            }
        }
    }
}

From source file:arduinouno.MainWindow.java

private void jButtonSelectFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSelectFileActionPerformed
    JFileChooser fileChooser = new JFileChooser();
    int returnVal = fileChooser.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        saveFile = fileChooser.getSelectedFile();
        jTextFieldSaveFile.setText(saveFile.getName());

    }//from w  w  w.  ja v a2 s. c om
}

From source file:kihira.tails.client.gui.GuiExport.java

@Override
protected void actionPerformed(GuiButton button) {
    //Export to file
    if (button.id == 0 || button.id == 1 || button.id == 2) {
        AbstractClientPlayer player = this.mc.thePlayer;
        File file;// w  w  w .  j  av  a2  s.  co m

        this.exportMessage = "";
        this.exportLoc = null;
        if (button.id == 0)
            file = new File(System.getProperty("user.home"));
        else if (button.id == 1)
            file = new File(System.getProperty("user.dir"));
        else {
            JFileChooser fileChooser = new JFileChooser(new File(System.getProperty("user.dir")));
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            if (fileChooser.showSaveDialog(Display.getParent()) == JFileChooser.APPROVE_OPTION) {
                file = fileChooser.getSelectedFile();
            } else
                return;
        }

        if (file.exists() && file.canWrite()) {
            this.exportLoc = file.toURI();
            file = new File(file, File.separatorChar + player.getCommandSenderName() + ".png");

            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    setExportMessage(
                            EnumChatFormatting.DARK_RED + String.format("Failed to create skin file! %s", e));
                    e.printStackTrace();
                }
            }

            BufferedImage image = TextureHelper.writePartsDataToSkin(this.partsData, player);
            if (image != null) {
                try {
                    ImageIO.write(image, "png", file);
                } catch (IOException e) {
                    setExportMessage(
                            EnumChatFormatting.DARK_RED + String.format("Failed to save skin file! %s", e));
                    e.printStackTrace();
                }
            } else {
                setExportMessage(
                        EnumChatFormatting.DARK_RED + String.format("Failed to export skin, image was null!"));
                file.delete();
            }
        }

        if (Strings.isNullOrEmpty(this.exportMessage)) {
            savePartsData();
            this.openFolderButton.visible = true;
            setExportMessage(EnumChatFormatting.GREEN + I18n.format("tails.export.success", file));
        }
    }
    if (button.id == 3 && this.exportLoc != null) {
        try {
            Desktop.getDesktop().browse(this.exportLoc);
        } catch (IOException e) {
            setExportMessage(
                    EnumChatFormatting.DARK_RED + String.format("Failed to open export location: %s", e));
            e.printStackTrace();
        }
    }

    //Upload
    if (button.id == 10) {
        final BufferedImage image = TextureHelper.writePartsDataToSkin(this.partsData, this.mc.thePlayer);
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                exportMessage = I18n.format("tails.uploading");
                new ImgurUpload().uploadImage(image);
            }
        };
        runnable.run();
    }
}

From source file:CompareFiles.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    // TODO add your handling code here:
    String userDir = System.getProperty("user.home");
    JFileChooser folder = new JFileChooser(userDir + "/Desktop");
    //        folder.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    folder.setFileSelectionMode(JFileChooser.FILES_ONLY);
    FileNameExtensionFilter xmlfilter = new FileNameExtensionFilter("Excel Files  (*.xls)", "xls");
    folder.setFileFilter(xmlfilter);/*  w  w  w. j  a v a  2  s . c  om*/
    int returnvalue = folder.showSaveDialog(this);

    File myfolder = null;
    if (returnvalue == JFileChooser.APPROVE_OPTION) {
        myfolder = folder.getSelectedFile();
        //            System.out.println(myfolder);         
    }

    if (myfolder != null) {
        JOptionPane.showMessageDialog(null, "The current choosen file directory is : " + myfolder);
        jLabel2.setText(myfolder.toString());
    }
}

From source file:CompareFiles.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    // TODO add your handling code here:

    String userDir = System.getProperty("user.home");
    JFileChooser folder = new JFileChooser(userDir + "/Desktop");
    folder.setFileSelectionMode(JFileChooser.FILES_ONLY);
    FileNameExtensionFilter xmlfilter = new FileNameExtensionFilter("Excel Files  (*.xls)", "xls");
    folder.setFileFilter(xmlfilter);//from w ww . j  a  v  a  2 s .  c om
    //        folder.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int returnvalue = folder.showSaveDialog(this);

    File myfolder = null;
    if (returnvalue == JFileChooser.APPROVE_OPTION) {
        myfolder = folder.getSelectedFile();
        //            System.out.println(myfolder);         
    }

    if (myfolder != null) {
        JOptionPane.showMessageDialog(null, "The current choosen file directory is : " + myfolder);
        jLabel1.setText(myfolder.toString());
    }

}

From source file:grafix.telas.TelaComparativos.java

private void salvarJPEG() {
    JFileChooser chooser = new JFileChooser();
    chooser.setSelectedFile(new File(".jpg"));
    int returnVal = chooser.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        try {/* ww w  . j av a 2  s.  c  o m*/
            ChartUtilities.saveChartAsJPEG(file, chartPanel.getChart(), chartPanel.getWidth(),
                    chartPanel.getHeight());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:de.biomedical_imaging.ij.plot.HistogramPlotter.java

public HistogramPlotter(String title, String xlabel, double[][] data, int numberOfParticles,
        int meanTrackLength, IDatasetCreator datacreator) {

    super(title);
    this.title = title;
    this.xlabel = xlabel;
    this.numberOfParticles = numberOfParticles;
    this.meanTrackLength = meanTrackLength;
    IntervalXYDataset xydataset = datacreator.create(data);
    boolean isbarplot = (datacreator instanceof BarplotDataset);
    txt = new JLabel();
    Font f = new Font("Verdana", Font.PLAIN, 12);
    txt.setFont(f);/*from w  ww  .  ja  va 2s .c  o m*/

    JFreeChart chart = createChart(xydataset, isbarplot);

    ChartPanel chartPanel = new ChartPanel(chart);

    txt.setText(formatSettingsString());

    main = new JPanel();
    main.setPreferredSize(new java.awt.Dimension(500, 350));
    main.add(chartPanel);
    main.add(txt);
    setContentPane(main);

    setLayout(new BoxLayout(main, BoxLayout.Y_AXIS));

    pack();
    setVisible(true);

    JMenuItem savebutton = ((JMenuItem) chartPanel.getPopupMenu().getComponent(3));
    chartPanel.getPopupMenu().remove(3); // Remove Save button
    //ActionListener al = savebutton.getActionListeners()[0];
    savebutton = new JMenuItem("Save as png");
    //savebutton.removeActionListener(al);
    savebutton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub

            try {
                JFileChooser saveFile = new JFileChooser();
                saveFile.setAcceptAllFileFilterUsed(false);
                saveFile.addChoosableFileFilter(new FileNameExtensionFilter("Images", "png"));
                int userSelection = saveFile.showSaveDialog(main);
                if (userSelection == JFileChooser.APPROVE_OPTION) {
                    BufferedImage bi = ScreenImage.createImage(main);
                    File fileToSave = saveFile.getSelectedFile();
                    String filename = fileToSave.getName();
                    int i = filename.lastIndexOf('.');
                    String suffix = filename.substring(i + 1);
                    String path = fileToSave.getAbsolutePath();
                    if (!(suffix.equals("png"))) {
                        path += ".png";
                    }
                    ScreenImage.writeImage(bi, path);
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                IJ.log("" + e.getMessage());
            }

        }
    });
    chartPanel.getPopupMenu().insert(savebutton, 3);

}

From source file:net.sf.mzmine.modules.visualization.ida.IDAPlot.java

@Override
public void actionPerformed(final ActionEvent event) {

    super.actionPerformed(event);

    final String command = event.getActionCommand();

    if ("SAVE_EMF".equals(command)) {

        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("EMF Image", "EMF");
        chooser.setFileFilter(filter);/*ww w.j  ava 2s.  c o m*/
        int returnVal = chooser.showSaveDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            String file = chooser.getSelectedFile().getPath();
            if (!file.toLowerCase().endsWith(".emf"))
                file += ".emf";

            int width = (int) this.getSize().getWidth();
            int height = (int) this.getSize().getHeight();

            // Save image
            SaveImage SI = new SaveImage(getChart(), file, width, height, FileType.EMF);
            new Thread(SI).start();

        }
    }

    if ("SAVE_EPS".equals(command)) {

        JFileChooser chooser = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("EPS Image", "EPS");
        chooser.setFileFilter(filter);
        int returnVal = chooser.showSaveDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            String file = chooser.getSelectedFile().getPath();
            if (!file.toLowerCase().endsWith(".eps"))
                file += ".eps";

            int width = (int) this.getSize().getWidth();
            int height = (int) this.getSize().getHeight();

            // Save image
            SaveImage SI = new SaveImage(getChart(), file, width, height, FileType.EPS);
            new Thread(SI).start();

        }

    }
}