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:pt.lsts.neptus.mra.exporters.MRAExporterFilter.java

private File chooseSaveFile(String path) {
    JFileChooser fileChooser = GuiUtils.getFileChooser(path, I18n.text("LSF logs"), FileUtil.FILE_TYPE_LSF,
            FileUtil.FILE_TYPE_LSF_COMPRESSED, FileUtil.FILE_TYPE_LSF_COMPRESSED_BZIP2);
    fileChooser.setSelectedFile(new File(path.concat("/Data_filtered.lsf.gz")));
    fileChooser.setAcceptAllFileFilterUsed(false);

    int status = fileChooser.showSaveDialog(ConfigFetch.getSuperParentFrame());
    String fileName = null;// w ww.ja va 2s  . c  o  m

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

        try {
            fileName = selectedFile.getCanonicalPath();
            if (fileName.endsWith("." + FileUtil.FILE_TYPE_LSF_COMPRESSED)
                    || fileName.endsWith("." + FileUtil.FILE_TYPE_LSF_COMPRESSED_BZIP2)) {
                return selectedFile = new File(fileName);
            }
            if (!fileName.endsWith("." + FileUtil.FILE_TYPE_LSF)) {
                return selectedFile = new File(fileName + "." + FileUtil.FILE_TYPE_LSF_COMPRESSED);
            }
            if (fileName.endsWith("." + FileUtil.FILE_TYPE_LSF)) {
                return selectedFile = new File(fileName);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:qrcode.JavaQR.java

@Override
public void run() {

    setLayout(new BorderLayout());

    JPanel topPanel = new JPanel();
    JPanel centerPanel = new JPanel();
    JPanel bottomPanel = new JPanel();

    topPanel.setLayout(new GridLayout(0, 1));
    topPanel.setBorder(BorderFactory.createTitledBorder("Input Data"));

    JPanel rowTopPanel = new JPanel();
    rowTopPanel.setLayout(new GridLayout(0, 2));

    JLabel accKey = new JLabel("Access Key");
    JTextField accField = new JTextField(5);

    accField.setEditable(false);// w  w w. j  av  a2s.co m
    accField.setText(Data.accessKey);

    JLabel regNo = new JLabel("Registration Number");
    JTextField regField = new JTextField(5);

    regField.setEditable(false);
    regField.setText(Data.registrationNumber);

    JLabel licNo = new JLabel("License Number");
    JFormattedTextField licField = new JFormattedTextField();

    licField.setEditable(false);
    licField.setText(Data.licenseNumber);

    rowTopPanel.add(accKey);
    rowTopPanel.add(accField);
    rowTopPanel.add(regNo);
    rowTopPanel.add(regField);
    rowTopPanel.add(licNo);
    rowTopPanel.add(licField);

    topPanel.add(rowTopPanel);

    centerPanel.setLayout(new GridLayout(0, 1));
    centerPanel.setBorder(BorderFactory.createTitledBorder("QR Code"));

    JPanel rowCenPanel = new JPanel();
    rowCenPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

    JButton genBtn = new JButton("Download QR Code");
    JButton homeBtn = new JButton("Back to Start");

    String accessKey = accField.getText().toString();
    String regKey = regField.getText().toString();
    String licKey = licField.getText().toString();
    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.put("accessKey", accessKey);
        jsonObject.put("registrationNumber", regKey);
        jsonObject.put("licenseNumber", licKey);
    } catch (JSONException e1) {
        e1.printStackTrace();
    }

    QRLogic qrGen = new QRLogic();
    BufferedImage image = qrGen.generateQR(jsonObject);
    centerPanel.add(new JLabel(new ImageIcon(image)));

    bottomPanel.setLayout(new GridLayout(2, 1));

    rowCenPanel.add(homeBtn);
    rowCenPanel.add(genBtn);
    bottomPanel.add(rowCenPanel);
    add(topPanel, BorderLayout.NORTH);
    add(bottomPanel, BorderLayout.SOUTH);
    add(centerPanel, BorderLayout.CENTER);
    Data.mainFrame.setSize(1000, 500);

    genBtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Date date = new Date();
            String newDate = new SimpleDateFormat("yyyy-MM-dd h-m-a").format(date);
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            File myFile = new File(Data.registrationNumber + ".png");
            fileChooser.setSelectedFile(myFile);
            fileChooser.showSaveDialog(null);
            String dlDir = fileChooser.getSelectedFile().getPath();
            System.out.println(dlDir);
            String fileName = fileChooser.getSelectedFile().getName();
            String filePath = "";
            if (fileName != null) {
                filePath = dlDir + ".png";
            } else {
                filePath = dlDir + "/" + Data.registrationNumber + ".png";
            }

            String fileType = "png";
            myFile = new File(filePath);

            if (dlDir != null) {

                try {
                    ImageIO.write(image, fileType, myFile);
                    JOptionPane.showMessageDialog(Data.mainFrame, "QR Code Saved in " + dlDir);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

            }
        }
    });

    homeBtn.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Data.mainFrame.showPanel("inventory");
        }
    });

    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    } catch (InstantiationException e1) {
        e1.printStackTrace();
    } catch (IllegalAccessException e1) {
        e1.printStackTrace();
    } catch (UnsupportedLookAndFeelException e1) {
        e1.printStackTrace();
    }

}

From source file:ro.nextreports.designer.wizimport.ImportPathSelectionWizardPanel.java

private void init() {
    setLayout(new BorderLayout());

    nameTextField = new JTextField();
    nameTextField.setPreferredSize(dim);
    nameTextField.setEditable(false);/*from w w  w  .jav  a 2s .c o  m*/

    propCheck = new JCheckBox(I18NSupport.getString("wizard.import.panel.start.select.title.prop"), true);

    selButton = new JButton();
    selButton.setPreferredSize(buttonDim);
    selButton.setMaximumSize(buttonDim);
    selButton.setMinimumSize(buttonDim);
    selButton.setIcon(ImageUtil.getImageIcon("folder"));
    selButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser();
            fc.setDialogTitle(I18NSupport.getString("import.long.desc"));
            fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int returnVal = fc.showSaveDialog((JDialog) context.getAttribute(ImportWizard.MAIN_FRAME));

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File f = fc.getSelectedFile();
                if (f != null) {
                    nameTextField.setText(f.getName());
                    path = f.getAbsolutePath();
                }
            }
        }
    });

    JPanel dsPanel = new JPanel(new GridBagLayout());
    dsPanel.add(new JLabel(I18NSupport.getString("wizard.import.panel.start.select.title.label")),
            new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE,
                    new Insets(5, 5, 5, 0), 0, 0));
    dsPanel.add(nameTextField, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.NONE, new Insets(5, 5, 5, 0), 0, 0));
    dsPanel.add(selButton, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
    dsPanel.add(propCheck, new GridBagConstraints(0, 1, 3, 1, 0.0, 0.0, GridBagConstraints.WEST,
            GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
    dsPanel.add(new JLabel(""), new GridBagConstraints(3, 1, 1, 2, 1.0, 1.0, GridBagConstraints.WEST,
            GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
    add(dsPanel, BorderLayout.CENTER);
}

From source file:ru.goodfil.catalog.ui.forms.MainWindow.java

/**
 *  //from  w w  w .j  a  v a 2  s.  c  o m
 *
 * @param e
 */
private void saveAsMenuItemActionPerformed(ActionEvent e) {
    try {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setSelectedFile(new File(new File("~/GoodwillCatalog.h2.db").getCanonicalPath()));
        fileChooser.setFileFilter(new FileNameExtensionFilter(" (*.h2.db)", "db"));
        int result = fileChooser.showSaveDialog(this);

        if (result == JFileChooser.APPROVE_OPTION) {
            File destinationFile = fileChooser.getSelectedFile();

            if (destinationFile != null) {
                sessionProvider.close();

                File database = new File(SessionFactoryHolder.getDatabasePathWithPrefix());

                try {
                    FileUtils.copyFile(database, destinationFile);
                } catch (IOException e1) {
                    e1.printStackTrace();
                    UIUtils.error("? ? ? !");
                }

                sessionProvider.init();
            }
        }
    } catch (Exception e2) {
        e2.printStackTrace();
    }
}

From source file:Samples.Advanced.GraphEditorDemo.java

/**
 * a driver for this demo//from w  ww .j a v a  2s  .  c  o  m
 */
@SuppressWarnings("serial")
public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final GraphEditorDemo demo = new GraphEditorDemo();

    JMenu menu = new JMenu("File");
    menu.add(new AbstractAction("Make Image") {
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            int option = chooser.showSaveDialog(demo);
            if (option == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                demo.writeJPEGImage(file);
            }
        }
    });
    menu.add(new AbstractAction("Print") {
        public void actionPerformed(ActionEvent e) {
            PrinterJob printJob = PrinterJob.getPrinterJob();
            printJob.setPrintable(demo);
            if (printJob.printDialog()) {
                try {
                    printJob.print();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    });
    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
    JMenuBar menuBar = new JMenuBar();
    menuBar.add(menu);
    JMenu matrixMenu = new JMenu();
    matrixMenu.setText("Matrix");
    matrixMenu.setIcon(null);
    matrixMenu.setPreferredSize(new Dimension(80, 20));
    menuBar.add(matrixMenu);
    JMenuItem copyMatrix = new JMenuItem("Copy Matrix to clipboard", KeyEvent.VK_C);
    copyMatrix.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
    menuBar.add(copyMatrix);
    frame.setJMenuBar(menuBar);
    frame.getContentPane().add(demo);
    copyMatrix.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            Vem textTransfer = new Vem();

            //Set up Matrix
            List<Integer[]> graphMatrix = new ArrayList<Integer[]>();
            int MatrixSize = graph.getVertexCount();

            Integer[] activeV = new Integer[MatrixSize];
            int count = 0;
            int activeVPos = 0;

            while (activeVPos < MatrixSize) {
                if (graph.containsVertex(count)) {
                    activeV[activeVPos] = count;
                    activeVPos++;
                }
                count++;
            }

            // sgv.g.getVertices().toArray()  ((Integer[])(sgv.g.getVertices().toArray()))
            for (int i = 0; i < MatrixSize; i++) {
                Integer[] tempArray = new Integer[MatrixSize];
                for (int j = 0; j < MatrixSize; j++) {
                    if (graph.findEdge(activeV[i], activeV[j]) != null) {
                        tempArray[j] = 1;
                    } else {
                        tempArray[j] = 0;
                    }
                }
                graphMatrix.add(tempArray);
            }
            //graphMatrix.add(new Integer[]{1, 2, 3});
            //graphMatrix.add(new Integer[]{4, 5 , 6, 7});

            //System.out.println(matrixToString(graphMatrix));
            //System.out.println(matrixToMathematica(graphMatrix));

            textTransfer.setClipboardContents("" + matrixToMathematica(graphMatrix));
            System.out.println("Clipboard contains:" + textTransfer.getClipboardContents());
        }
    });

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

From source file:Samples.Advanced.GraphEditorDemo2.java

/**
 * a driver for this demo//from ww w .j  av a  2  s.com
 */
@SuppressWarnings("serial")
public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final GraphEditorDemo2 demo = new GraphEditorDemo2();

    JMenu menu = new JMenu("File");
    menu.add(new AbstractAction("Make Image") {
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();
            int option = chooser.showSaveDialog(demo);
            if (option == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                demo.writeJPEGImage(file);
            }
        }
    });
    menu.add(new AbstractAction("Print") {
        public void actionPerformed(ActionEvent e) {
            PrinterJob printJob = PrinterJob.getPrinterJob();
            printJob.setPrintable(demo);
            if (printJob.printDialog()) {
                try {
                    printJob.print();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    });
    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
    JMenuBar menuBar = new JMenuBar();
    menuBar.add(menu);
    frame.setJMenuBar(menuBar);
    frame.getContentPane().add(demo);
    frame.pack();
    frame.setVisible(true);
}

From source file:sc.fiji.kappa.gui.CurvesExporter.java

public void export(boolean exportAveragePerCurve) throws IOException {

    JFileChooser kappaExport = new JFileChooser();

    String dirPath = frame.getImageStack().getOriginalFileInfo().directory;
    if (dirPath != null) {
        String kappaPath = FilenameUtils.removeExtension(frame.getImageStack().getOriginalFileInfo().fileName);
        kappaPath += ".csv";
        File fullPath = new File(dirPath, kappaPath);
        kappaExport.setSelectedFile(fullPath);
    }/*from  w  w w.  ja v  a  2s. c om*/

    kappaExport.setFileFilter(new FileNameExtensionFilter("CSV File", "csv"));
    kappaExport.setDialogTitle("Export Curve Data");

    // Handles export button action.
    int returnVal = kappaExport.showSaveDialog(frame);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = kappaExport.getSelectedFile();
        exportToFile(file, exportAveragePerCurve);
    }
}

From source file:se.cambio.cds.gdl.editor.controller.GDLEditor.java

public void saveCompiledGuideAsObject(byte[] compiledGuide, Guide guide) {
    GDLEditor controller = EditorManager.getActiveGDLEditor();
    String idGuide = controller.getIdGuide();
    if (idGuide == null) {
        idGuide = GDLEditorLanguageManager.getMessage("Guide");
    }/*w  ww .ja  v a2 s  .c o m*/
    if (compiledGuide != null) {
        try {
            String guideSource = controller.serializeCurrentGuide();
            if (guideSource != null) {
                JFileChooser fileChooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                        GDLEditorLanguageManager.getMessage("Guide"), new String[] { "guide" });
                fileChooser.setDialogTitle(GDLEditorLanguageManager.getMessage("SaveGuideAsObjectSD"));
                fileChooser.setFileFilter(filter);
                File file = new File(
                        fileChooser.getFileSystemView().getDefaultDirectory() + "/" + idGuide + ".guide");
                fileChooser.setSelectedFile(file);
                int result = fileChooser.showSaveDialog(EditorManager.getActiveEditorWindow());
                File guideFile = fileChooser.getSelectedFile();
                if (result != JFileChooser.CANCEL_OPTION) {
                    idGuide = guideFile.getName();
                    if (idGuide.endsWith(".guide")) {
                        idGuide = idGuide.substring(0, idGuide.length() - 6);
                    }
                    GuideDTO guideDTO = new GuideDTO(idGuide, guideSource, IOUtils.getBytes(guide),
                            compiledGuide, true, Calendar.getInstance().getTime());
                    ObjectOutputStream output = new ObjectOutputStream(
                            new BufferedOutputStream(new FileOutputStream(guideFile)));
                    try {
                        output.writeObject(guideDTO);
                    } catch (Exception e) {
                        ExceptionHandler.handle(e);
                    } finally {
                        output.close();
                    }
                }
            }
        } catch (Exception e) {
            ExceptionHandler.handle(e);
        }
    }
}

From source file:se.cambio.cds.util.ExportUtils.java

public static void exportToHTML(Window owner, Guide guide, String lang) {
    JFileChooser fileChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("HTML", new String[] { "html" });
    fileChooser.setDialogTitle(OpenEHRLanguageManager.getMessage("ExportToHTML"));
    fileChooser.setFileFilter(filter);/* w w  w .  j a  va2  s .  c  o  m*/
    File selectedFile = new File(guide.getId() + ".html");
    fileChooser.setSelectedFile(selectedFile);
    int result = fileChooser.showSaveDialog(owner);
    if (result != JFileChooser.CANCEL_OPTION) {
        try {
            selectedFile = fileChooser.getSelectedFile();
            FileWriter fstream = new FileWriter(selectedFile);
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(convertToHTML(guide, lang));
            out.close();
        } catch (IOException e) {
            ExceptionHandler.handle(e);
        } catch (InternalErrorException e) {
            ExceptionHandler.handle(e);
        }
    }
}

From source file:su.fmi.photoshareclient.ui.PhotoViewDialog.java

private void SaveImageButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_SaveImageButtonMouseClicked
    JFileChooser fileChooser = new JFileChooser() {
        // A warning for overweiting existing files
        @Override/*ww w.j  a v a2  s .com*/
        public void approveSelection() {
            File f = getSelectedFile();
            if (f.exists() && getDialogType() == SAVE_DIALOG) {
                int result = JOptionPane.showConfirmDialog(this, "The file exists, overwrite?", "Existing file",
                        JOptionPane.YES_NO_CANCEL_OPTION);
                switch (result) {
                case JOptionPane.YES_OPTION:
                    super.approveSelection();
                    return;
                case JOptionPane.NO_OPTION:
                    return;
                case JOptionPane.CLOSED_OPTION:
                    return;
                case JOptionPane.CANCEL_OPTION:
                    cancelSelection();
                    return;
                }
            }
            super.approveSelection();
        }
    };
    fileChooser.setDialogTitle("Save image as...");
    File rootVolume = File.listRoots()[0];
    fileChooser.setSelectedFile(new File(rootVolume.getAbsolutePath(), this.imageLabel.getFileName()));

    int userSelection = fileChooser.showSaveDialog(this);

    if (userSelection == JFileChooser.APPROVE_OPTION) {
        try {
            File fileToSave = fileChooser.getSelectedFile();
            BufferedImage bi = (BufferedImage) this.imageLabel.getImage();
            String ext = FilenameUtils.getExtension(fileToSave.getAbsolutePath());
            ImageIO.write(bi, ext, fileToSave);
        } catch (IOException ex) {
            Logger.getLogger(PhotoViewDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}