Example usage for javax.swing JFileChooser APPROVE_OPTION

List of usage examples for javax.swing JFileChooser APPROVE_OPTION

Introduction

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

Prototype

int APPROVE_OPTION

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

Click Source Link

Document

Return value if approve (yes, ok) is chosen.

Usage

From source file:SciTK.Plot.java

/** 
* Save displayed chart as vector graphics 
*//*from  w  ww  .j a va  2s  . c  o m*/
public void saveVectorGraphics() {
    Rectangle r = chart_panel.getBounds(); // get size of chart

    // file selection:
    JFileChooser fc = new JFileChooser();
    fc.addChoosableFileFilter(new ExtensionFileFilter("SVG", new String[] { "svg,SVG" }));
    fc.addChoosableFileFilter(new ExtensionFileFilter("PS", new String[] { "ps,PS" }));
    fc.addChoosableFileFilter(new ExtensionFileFilter("EPS", new String[] { "eps,EPS" }));
    // remove default option:
    fc.setAcceptAllFileFilterUsed(false);

    // Select a file using the JFileChooser dialog:
    int fc_return = fc.showSaveDialog(Plot.this);

    // if the user actually wants to save:
    if (fc_return == JFileChooser.APPROVE_OPTION) {
        //get the file:
        File save_file = fc.getSelectedFile();
        // and the type of extension (from file chooser)
        String extension = fc.getFileFilter().getDescription();
        try // try/catch for IO errors
        {
            // For each type of extension, check to see if the name includes the
            // correct extension and then save the image to file.
            // Default extension is EPS
            if (extension == "SVG") {
                // sanity check extension:
                if (!save_file.getName().endsWith(".svg") && !save_file.getName().endsWith(".SVG"))
                    save_file = new File(save_file.getAbsolutePath() + ".svg");
                exportChartAsSVG(chart, r, save_file);
            } else if (extension == "PS") {
                // sanity check extension:
                if (!save_file.getName().endsWith(".ps") && !save_file.getName().endsWith(".PS"))
                    save_file = new File(save_file.getAbsolutePath() + ".ps");
                exportChartAsPS(chart, r, save_file, "ps");
            } else {
                // sanity check extension:
                if (!save_file.getName().endsWith(".eps") && !save_file.getName().endsWith(".EPS"))
                    save_file = new File(save_file.getAbsolutePath() + ".eps");
                exportChartAsPS(chart, r, save_file, "eps");
            }
        } catch (IOException e) {
            DialogError emsg = new DialogError(this, " There was an error saving the file."
                    + System.getProperty("line.separator") + e.getMessage());
        }
    }
}

From source file:com.emental.mindraider.ui.dialogs.AttachmentJDialog.java

/**
 * Concetructor.//from www  .  j  a v  a  2s  .c  om
 * 
 * @param noteResource
 *            The concept resource.
 * @param dragAndDropReference
 *            The drag'n'drop reference.
 */
public AttachmentJDialog(ConceptResource conceptResource, DragAndDropReference dragAndDropReference) {

    super(Messages.getString("AttachmentJDialog.title"));
    this.conceptResource = conceptResource;
    getContentPane().setLayout(new BorderLayout());
    JPanel p, pp;

    p = new JPanel();
    p.setLayout(new BorderLayout());
    JLabel intro = new JLabel("<html>&nbsp;&nbsp;" + Messages.getString("AttachmentJDialog.introduction")
            + "&nbsp;&nbsp;<br><br></html>");
    p.add(intro, BorderLayout.NORTH);
    p.add(new JLabel("<html>&nbsp;&nbsp;" + Messages.getString("AttachmentJDialog.description") + "</html>"),
            BorderLayout.CENTER);
    description = new JTextField(38);
    pp = new JPanel(new FlowLayout(FlowLayout.LEFT));
    pp.add(description);
    p.add(pp, BorderLayout.SOUTH);
    getContentPane().add(p, BorderLayout.NORTH);

    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BorderLayout());
    mainPanel.setBorder(new TitledBorder(Messages.getString("AttachmentJDialog.resource")));

    ButtonGroup attachType = new ButtonGroup();

    JPanel webPanel = new JPanel();
    webPanel.setLayout(new BorderLayout());
    webType = new JRadioButton(Messages.getString("AttachmentJDialog.web"));
    webType.setActionCommand(WEB);
    webType.addActionListener(this);
    webType.setSelected(true);
    attachType.add(webType);
    webPanel.add(webType, BorderLayout.NORTH);
    urlTextField = new JTextField("http://", 35);
    urlTextField.selectAll();
    urlTextField.addKeyListener(new KeyListener() {

        public void keyPressed(KeyEvent keyEvent) {
            if (keyEvent.getKeyCode() == KeyEvent.VK_ENTER) {
                attach();
            }
        }

        public void keyReleased(KeyEvent keyEvent) {
        }

        public void keyTyped(KeyEvent keyEvent) {
        }
    });
    p = new JPanel();
    p.setLayout(new FlowLayout(FlowLayout.LEFT));
    p.add(new JLabel("   "));
    p.add(urlTextField);
    webPanel.add(p, BorderLayout.SOUTH);
    mainPanel.add(webPanel, BorderLayout.NORTH);

    JPanel localPanel = new JPanel();
    localPanel.setLayout(new BorderLayout());
    JRadioButton localType = new JRadioButton(Messages.getString("AttachmentJDialog.local"));
    localType.setActionCommand(LOCAL);
    localType.addActionListener(this);
    localPanel.add(localType, BorderLayout.NORTH);
    pathTextField = new JTextField(35);
    pathTextField.setEnabled(false);
    browseButton = new JButton(Messages.getString("AttachmentJDialog.browse"));
    browseButton.setToolTipText(Messages.getString("AttachmentJDialog.browseTip"));
    browseButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser();
            fc.setApproveButtonText(Messages.getString("AttachmentJDialog.attach"));
            fc.setControlButtonsAreShown(true);
            fc.setDialogTitle(Messages.getString("AttachmentJDialog.chooseAttachment"));
            fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            int returnVal = fc.showOpenDialog(AttachmentJDialog.this);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                pathTextField.setText(file.toString());
            }
        }
    });
    browseButton.setEnabled(false);
    pp = new JPanel();
    pp.setLayout(new BorderLayout());
    p = new JPanel();
    p.setLayout(new FlowLayout(FlowLayout.LEFT));
    p.add(new JLabel("   "));
    pp.add(p, BorderLayout.NORTH);
    p.add(pathTextField);
    p = new JPanel();
    p.setLayout(new FlowLayout(FlowLayout.RIGHT));
    p.add(browseButton);
    pp.add(p, BorderLayout.SOUTH);
    localPanel.add(pp, BorderLayout.SOUTH);
    attachType.add(localType);
    mainPanel.add(localPanel, BorderLayout.SOUTH);

    getContentPane().add(mainPanel, BorderLayout.CENTER);

    // buttons
    p = new JPanel();
    p.setLayout(new FlowLayout(FlowLayout.CENTER));
    JButton addButton = new JButton(Messages.getString("AttachmentJDialog.attach"));

    p.add(addButton);
    addButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            attach();
        }
    });
    JButton cancelButton = new JButton(Messages.getString("AttachmentJDialog.cancel"));
    p.add(cancelButton);
    cancelButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            AttachmentJDialog.this.dispose();
        }
    });
    getContentPane().add(p, BorderLayout.SOUTH);

    /*
     * drag and drop initialization
     */
    if (dragAndDropReference != null) {
        if (dragAndDropReference.getType() == DragAndDropReference.BROWSER_LINK) {
            urlTextField.setText(dragAndDropReference.getReference());
            localType.setSelected(false);
            webType.setSelected(true);
            enableWebTypeButtons();
        } else {
            pathTextField.setText(dragAndDropReference.getReference());
            localType.setSelected(true);
            webType.setSelected(false);
            enableLocalTypeButtons();
        }
        description.setText(dragAndDropReference.getTitle());
    }

    pack();
    Gfx.centerAndShowWindow(this);
}

From source file:it.unibo.alchemist.boundary.gui.Perspective.java

private void openFile() {
    final JFileChooser fc = new JFileChooser();
    fc.setMultiSelectionEnabled(false);// w w w .  j av  a2 s . c om
    fc.setFileFilter(FILE_FILTER);
    fc.setCurrentDirectory(currentDirectory);
    final int returnVal = fc.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        fileToLoad = fc.getSelectedFile();
        currentDirectory = fc.getSelectedFile().getParentFile();
        if (fileToLoad.exists()) {
            status.setText(getString("ready_to_process") + " " + fileToLoad.getAbsolutePath());
            status.setOK();
            if (sim != null) {
                sim.addCommand(new Engine.StateCommand<T>().stop().build());
            }
            bar.setFileOK(true);
        } else {
            status.setText(FILE_NOT_VALID + " " + fileToLoad.getAbsolutePath());
            status.setNo();
            bar.setFileOK(false);
        }
    }
}

From source file:client.ui.UploadFileWindow.java

private void pathButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_pathButtonActionPerformed
    JFileChooser fileWindow = new JFileChooser();
    int confirm = fileWindow.showOpenDialog(null);
    if (confirm == JFileChooser.APPROVE_OPTION) {
        String filePath = fileWindow.getSelectedFile().getPath();
        String filename = fileWindow.getSelectedFile().getName();
        pathField.setText(filePath);//  w w w. j a va 2 s . c om
        filenameField.setText(filename);
    }
}

From source file:es.emergya.ui.gis.popups.ListaCapas.java

private JButton getCargarGPXButton() {
    JButton cargar = new JButton(i18n.getString("window.gpx.button.load"),
            LogicConstants.getIcon("historico_button_cargargpx"));
    cargar.addActionListener(new ActionListener() {

        @Override/*from  w ww  . jav  a2  s. co  m*/
        public void actionPerformed(ActionEvent e) {
            fileChooser = new JFileChooser();
            fileChooser.setFileFilter(new FileFilter() {

                @Override
                public boolean accept(File f) {
                    if (f.isDirectory()) {
                        return true;
                    }
                    return (f.getName().toLowerCase().endsWith(".gpx"));
                }

                @Override
                public String getDescription() {
                    return i18n.getString("window.gpx.filechooser.filter");
                }
            });

            try {
                if (fileChooser.showOpenDialog(self) == JFileChooser.APPROVE_OPTION) {
                    cargarGpx(fileChooser.getSelectedFile());
                }
            } catch (Throwable t) {
                log.error("Error al cargar GPX " + t);
                JOptionPane.showMessageDialog(getBasicWindow().getFrame(),
                        i18n.getString("window.gpx.loadError"));
            }
        }
    });
    return cargar;
}

From source file:view.MainFrame.java

private void menuItemOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemOpenActionPerformed
    // TODO add your handling code here:
    JFileChooser filech = new JFileChooser();
    filech.setFileSelectionMode(JFileChooser.FILES_ONLY);
    filech.setFileFilter(new FileNameExtensionFilter("WAV Files", "wav"));
    int ret = filech.showOpenDialog(this);

    if (ret == JFileChooser.APPROVE_OPTION) {
        try {/*from  ww  w .  java 2  s .  co m*/
            wavFile = WavFile.openWavFile(filech.getSelectedFile());
            textArea.append(wavFile.getInfoString());
            samples = new double[wavFile.getNumChannels() * (int) wavFile.getSampleRate()];
            int nFrames = wavFile.readFrames(samples, (int) wavFile.getSampleRate());
            textArea.append(nFrames + " frames lidos.\n");

            double valuesX[] = new double[samples.length];
            for (int i = 0; i < samples.length; i++) {
                valuesX[i] = i;
            }

            showChart(wavFile.getNumChannels() * (int) wavFile.getSampleRate(), samples, valuesX, "Amostra",
                    "Amplitude", "Amplitude das Amostras do ?udio", "Audio");
        } catch (IOException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (WavFileException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:edu.mit.fss.examples.member.gui.PowerSubsystemPanel.java

/**
 * Export this panel's generation dataset.
 *//*from w ww. j  av a 2s.co m*/
private void exportDataset() {
    if (JFileChooser.APPROVE_OPTION == fileChooser.showSaveDialog(this)) {
        File f = fileChooser.getSelectedFile();

        if (!f.exists() || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this,
                "Overwrite existing file " + f.getName() + "?", "File Exists", JOptionPane.YES_NO_OPTION)) {

            logger.info("Exporting dataset to file " + f.getPath() + ".");
            try {
                BufferedWriter bw = Files.newBufferedWriter(Paths.get(f.getPath()), Charset.defaultCharset());

                StringBuilder b = new StringBuilder();
                b.append(" Generation\n").append("Time, Value\n");
                for (int j = 0; j < generationSeries.getItemCount(); j++) {
                    b.append(generationSeries.getTimePeriod(j).getStart().getTime()).append(", ")
                            .append(generationSeries.getValue(j)).append("\n");
                }

                bw.write(b.toString());
                bw.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
    }
}

From source file:eu.novait.imagerenamer.gui.MainWindow.java

protected void saveFiles() {
    if (chooser == null) {
        chooser = new JFileChooser();
    }//w w  w .  jav a 2s . co  m
    for (FileFilter ff : chooser.getChoosableFileFilters()) {
        chooser.removeChoosableFileFilter(ff);
    }
    chooser.setMultiSelectionEnabled(false);
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);
    int returnVal = chooser.showSaveDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        loaderBar.setMaximum(imageTableModel.getRowCount());
        loaderBar.setValue(0);
        this.setCurrentState(STATE_SAVING);
        Thread renameThread = new Thread(new Runnable() {

            @Override
            public void run() {
                File dstDir = chooser.getSelectedFile();
                for (ImageFile imageFile : imageTableModel.getList()) {
                    System.out.println(dstDir.getAbsolutePath());
                    loaderBar.setValue(loaderBar.getValue() + 1);
                    //FileUtils.copyFile(dstDir, dstDir);
                }
                setCurrentState(STATE_WAITING);
            }
        });
    }
}

From source file:com.sciaps.utils.Util.java

public static ArrayList<SpectrumShotItem> readCSVFile() {
    ArrayList<SpectrumShotItem> shotItems = new ArrayList<SpectrumShotItem>();

    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(new FileNameExtensionFilter("CSV files", "csv", "CSV"));

    int retrival = chooser.showOpenDialog(null);
    if (retrival == JFileChooser.APPROVE_OPTION) {

        ProgressStatusPanel progressbar = new ProgressStatusPanel();
        final CustomDialog progressDialog = new CustomDialog(Constants.MAIN_FRAME, "Importing CSV file",
                progressbar, CustomDialog.NONE_OPTION);
        progressDialog.setSize(400, 100);
        SwingUtilities.invokeLater(new Runnable() {

            @Override//from  w ww.j  av a 2  s .com
            public void run() {
                progressDialog.setVisible(true);
            }
        });

        try {
            FileReader fr = new FileReader(chooser.getSelectedFile());
            BufferedReader br = new BufferedReader(fr);
            String line;

            while ((line = br.readLine()) != null) {
                shotItems.add(packSpectrumShotItem(line));
            }
            br.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("Exception: " + ex.getMessage());
        }

        progressDialog.dispose();
    }

    return shotItems;
}

From source file:com.opendoorlogistics.core.utils.ui.FileBrowserPanel.java

private static JButton createBrowseButton(final boolean directoriesOnly, final String browserApproveButtonText,
        final JTextField textField, final FileFilter... fileFilters) {
    JButton browseButton = new JButton("...");
    browseButton.addActionListener(new ActionListener() {

        @Override//  w ww.  j a  va 2s  .  co  m
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser = new JFileChooser();

            if (textField.getText() != null) {
                File file = new File(textField.getText());

                // if the file doesn't exist but the directory does, get that
                if (!file.exists() && file.getParentFile() != null && file.getParentFile().exists()) {
                    file = file.getParentFile();
                }

                if (!directoriesOnly && file.isFile()) {
                    chooser.setSelectedFile(file);
                }

                if (file.isDirectory() && file.exists()) {
                    chooser.setCurrentDirectory(file);
                }
            }

            if (directoriesOnly) {
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            }

            // add filters and automatically select correct one
            if (fileFilters.length == 1) {
                chooser.setFileFilter(fileFilters[0]);
            } else {
                for (FileFilter filter : fileFilters) {
                    chooser.addChoosableFileFilter(filter);
                    if (filter instanceof FileNameExtensionFilter) {
                        if (matchesFilter((FileNameExtensionFilter) filter, textField.getText())) {
                            chooser.setFileFilter(filter);
                        }
                    }
                }
            }

            if (chooser.showDialog(textField, browserApproveButtonText) == JFileChooser.APPROVE_OPTION) {
                //File selected = processSelectedFile(chooser.getSelectedFile());
                File selected = chooser.getSelectedFile();

                String path = selected.getPath();
                FileFilter filter = chooser.getFileFilter();
                if (filter != null && filter instanceof FileNameExtensionFilter) {

                    boolean found = matchesFilter(((FileNameExtensionFilter) chooser.getFileFilter()), path);

                    if (!found) {
                        String[] exts = ((FileNameExtensionFilter) chooser.getFileFilter()).getExtensions();
                        if (exts.length > 0) {
                            path = FilenameUtils.removeExtension(path);
                            path += "." + exts[0];
                        }
                    }

                }
                textField.setText(path);
            }
        }
    });

    return browseButton;
}