Example usage for javax.swing JFileChooser getSelectedFile

List of usage examples for javax.swing JFileChooser getSelectedFile

Introduction

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

Prototype

public File getSelectedFile() 

Source Link

Document

Returns the selected file.

Usage

From source file:net.panthema.BispanningGame.MyGraphMLReader.java

MyGraphMLReader(javax.swing.JPanel panel) throws FileNotFoundException, GraphIOException {

    posMap = new TreeMap<Integer, Point2D>();

    // Query user for filename
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Specify GraphML file to read");
    chooser.setCurrentDirectory(new File("."));
    FileNameExtensionFilter filter = new FileNameExtensionFilter("GraphML File", "graphml");
    chooser.setFileFilter(filter);/*from   ww w  . j  a va  2  s . c o m*/

    if (chooser.showOpenDialog(panel) != JFileChooser.APPROVE_OPTION)
        return;

    File infile = chooser.getSelectedFile();

    BufferedReader fileReader = new BufferedReader(new FileReader(infile));

    newGraph = new MyGraph();

    // create the graph transformer
    Transformer<GraphMetadata, MyGraph> graphTransformer = new Transformer<GraphMetadata, MyGraph>() {
        public MyGraph transform(GraphMetadata metadata) {
            assert (metadata.getEdgeDefault().equals(EdgeDefault.UNDIRECTED));
            return newGraph;
        }
    };

    // create the vertex transformer
    Transformer<NodeMetadata, Integer> vertexTransformer = new Transformer<NodeMetadata, Integer>() {
        public Integer transform(NodeMetadata metadata) {
            // create a new vertex
            Integer v = newGraph.getVertexCount();

            // save layout information
            if (metadata.getProperty("x") != null && metadata.getProperty("y") != null) {
                double x = Double.parseDouble(metadata.getProperty("x"));
                double y = Double.parseDouble(metadata.getProperty("y"));
                posMap.put(v, new Point2D.Double(x, y));
            }

            newGraph.addVertex(v);
            return v;
        }
    };

    // create the edge transformer
    Transformer<EdgeMetadata, MyEdge> edgeTransformer = new Transformer<EdgeMetadata, MyEdge>() {
        public MyEdge transform(EdgeMetadata metadata) {
            MyEdge e = new MyEdge(newGraph.getEdgeCount());
            if (metadata.getProperty("color") != null)
                e.color = Integer.parseInt(metadata.getProperty("color"));
            return e;
        }
    };

    // create the useless hyperedge transformer
    Transformer<HyperEdgeMetadata, MyEdge> hyperEdgeTransformer = new Transformer<HyperEdgeMetadata, MyEdge>() {
        public MyEdge transform(HyperEdgeMetadata metadata) {
            return null;
        }
    };

    // create the graphMLReader2
    GraphMLReader2<MyGraph, Integer, MyEdge> graphReader = new GraphMLReader2<MyGraph, Integer, MyEdge>(
            fileReader, graphTransformer, vertexTransformer, edgeTransformer, hyperEdgeTransformer);

    // Get the new graph object from the GraphML file
    graphReader.readGraph();
}

From source file:com.view.Main.java

private void filePathBrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filePathBrowseButtonActionPerformed
    final JFileChooser fileChooser = new JFileChooser(".");
    final FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel files", "xlsx", "xls");
    fileChooser.addChoosableFileFilter(filter);
    fileChooser.setFileFilter(filter);//from w  w w .  j av a  2s  . c om
    int result = fileChooser.showDialog(this, "choose a file");
    if (result == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fileChooser.getSelectedFile();
        filePathTextField.setText(selectedFile.getAbsolutePath());
    }

}

From source file:org.fhcrc.cpl.toolbox.gui.chart.PanelWithChart.java

/**
 * Add two new menu items to the popup menu, for saving to TSV and CSV files
 *///from   ww  w .j  a  v  a  2  s . co  m
protected void initPopupMenu() {
    addSeparatorToPopupMenu();

    //TSV
    JMenuItem saveTSVMenuItem = new JMenuItem(TextProvider.getText("SAVE_DATA_AS_TSV"));
    saveTSVMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            JFileChooser fc = new JFileChooser();
            int chooserStatus = fc.showOpenDialog(PanelWithChart.this);
            //if user didn't hit OK, ignore
            if (chooserStatus != JFileChooser.APPROVE_OPTION)
                return;

            File outFile = fc.getSelectedFile();
            saveChartDataToTSV(outFile);
        }
    });
    addItemToPopupMenu(saveTSVMenuItem);

    //CSV
    JMenuItem saveCSVMenuItem = new JMenuItem(TextProvider.getText("SAVE_DATA_AS_CSV"));
    saveCSVMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            JFileChooser wfc = new JFileChooser();
            int chooserStatus = wfc.showOpenDialog(PanelWithChart.this);
            //if user didn't hit OK, ignore
            if (chooserStatus != JFileChooser.APPROVE_OPTION)
                return;

            File outFile = wfc.getSelectedFile();
            saveChartDataToCSV(outFile);
        }
    });
    addItemToPopupMenu(saveCSVMenuItem);
}

From source file:modelibra.swing.app.util.FileSelector.java

/**
 * Selects a directory (path)./* w  w  w  .  j av a2 s . co  m*/
 * 
 * @param lang
 *            language
 * @return chosen directory path
 */
public String selectDirectory(NatLang lang) {
    JFileChooser dirChooser = new JFileChooser(lastDirectoryPath);
    dirChooser.setLocale(lang.getLocale());
    dirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    dirChooser.setToolTipText(lang.getText("selectDirectory"));
    dirChooser.setDialogTitle(lang.getText("selectDirectory"));
    dirChooser.showDialog(null, lang.getText("selectDirectory"));
    File f = dirChooser.getSelectedFile();
    if (f != null) {
        lastDirectoryPath = f.getPath();
        return lastDirectoryPath;
    } else {
        return null;
    }
}

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 w w .  j a  v  a2s . co  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:wsattacker.plugin.intelligentdos.ui.dialog.Result_NB.java

private void saveBtnActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_saveBtnActionPerformed
    try {/*from   w w  w .  j a  va2s. com*/
        JFileChooser fileChooser = new JFileChooser();
        int checker = fileChooser.showOpenDialog(null);
        if (checker == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            String message = "The selected file already exists.\nOverwrite?";
            if (!selectedFile.exists() || JOptionPane.showConfirmDialog(this, message, "Save result",
                    JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {

                if (!FilenameUtils.getExtension(selectedFile.getName()).equalsIgnoreCase(FILE_EXT_ZIP)) {
                    selectedFile = new File(selectedFile.getAbsoluteFile() + "." + FILE_EXT_ZIP);
                }

                btnController.save(selectedFile);
                // default title and icon
                JOptionPane.showMessageDialog(this, "Result has been saved to filesystem.");
            }
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, e.getMessage(), "Fehler beim Schreiben", JOptionPane.ERROR_MESSAGE);
        logger.warn(e, e);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:filesscanner.MainWindow.java

private void scanBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_scanBtnActionPerformed
    File f = new File("C:");
    JFileChooser chooser = ShowChooser(f);
    int res = chooser.showDialog(this, " ");

    if (res == JFileChooser.APPROVE_OPTION) {

        File[] files = chooser.getSelectedFiles();

        int key = 0;
        for (File file : files) {
            modelDirectories.add(key++, chooser.getSelectedFile().toString());
        }//from  w  w  w  . java 2s.  c o  m

    }
}

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  w  w  .jav  a 2  s  . c  o  m
            Matrix.writeToFile(m, file.getAbsolutePath(), ';', 5);
        } catch (IOException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }
    }
}

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 {//  w  ww .j  a  v a2 s.c om
            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:de.stefanwndelmann.zy1270logger.ZY1270LoggerMain.java

private void saveCSVButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveCSVButtonActionPerformed
    // TODO add your handling code here:
    String data = getCSVData();//from  w w w.j a va 2 s .c o m
    JFileChooser chooser = new JFileChooser();
    chooser.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv"));
    int retrival = chooser.showSaveDialog(null);
    if (retrival == JFileChooser.APPROVE_OPTION) {
        try (FileWriter fw = new FileWriter(chooser.getSelectedFile() + ".csv")) {
            fw.write(data);
        } catch (IOException ex) {
            Logger.getLogger(ZY1270LoggerMain.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}