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:Main.java

/**
 * Displays a {@link JFileChooser} to select a directory.
 *
 * @param title The title of the dialog.
 * @param startDirectory The directory where the dialog is initialed opened.
 * @return The {@link File} selected, returns null if no directory was selected.
 *///  www .  ja v  a2s . c o  m
public static File chooseDirectory(String title, File startDirectory) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setDialogTitle(title);

    if (startDirectory != null) {
        chooser.setCurrentDirectory(startDirectory);
    }

    int status = chooser.showOpenDialog(null);

    if (status == JFileChooser.APPROVE_OPTION) {
        return chooser.getSelectedFile();
    }

    return null;
}

From source file:jgraph.JShow.java

/**
 * a driver for this demo//from w w  w  .jav a 2 s . c o m
 */
@SuppressWarnings("serial")
public static void showtest(DirectedOrderedSparseMultigraph<Object, Object> graph) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    final JShow demo = new JShow(graph);

    JMenu menu = new JMenu("Snapshot");
    menu.add(new AbstractAction("To JPEG") {
        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:br.univali.ps.fuzzy.portugolFuzzyCorretor.control.FileController.java

public static String getCodigoPortugol() throws FileNotFoundException {
    JFileChooser fc = new JFileChooser(currentDirectory);
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Portugol Code", "por", "txt");
    fc.setFileFilter(filter);/*from ww  w  . ja va2s .  com*/
    fc.setAcceptAllFileFilterUsed(false);
    File file = null;
    int returnVal = fc.showOpenDialog(null);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        file = fc.getSelectedFile();
        currentDirectory = file.getParentFile().getPath();
        return formatarArquivoTexto(file);
    }
    return "";
}

From source file:my.grafos.Maquina.java

static void salvarGrafo() throws FileNotFoundException, IOException {
    /*//from  ww w  . java  2s .c o m
    FileOutputStream fos = new FileOutputStream("d:\\t.xml");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(Fabrica.listaArestas);
    oos.close();
     */
    final JFileChooser fc = new JFileChooser();
    //Handle save button action.
    int returnVal = fc.showSaveDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        System.out.println("1 " + fc.getSelectedFile());
        System.out.println("2 " + file);
        //            if (Fabrica.xmlA.length() == 0) {
        if (Fabrica.xmlA.length() == 0) {
            //                System.out.println("No h dados para salvar.");
            return;
        }
        try (OutputStream output = new FileOutputStream(file.getPath())) {
            int count = 0;

            while (count < Fabrica.xmlA.length()) {
                output.write(Fabrica.xmlA.charAt(count));
                count++;
            }
            count = 0;
            while (count < Fabrica.xmlV.length()) {
                output.write(Fabrica.xmlV.charAt(count));
                count++;
            }
        } catch (IOException e) {
        }
    }

}

From source file:net.rptools.maptool.util.AssetExtractor.java

public static void extract() throws Exception {
    new Thread() {
        @Override/*from  ww  w  . j a v a2s.c o  m*/
        public void run() {
            JFileChooser chooser = new JFileChooser();
            chooser.setMultiSelectionEnabled(false);
            chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            if (chooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION) {
                return;
            }
            File file = chooser.getSelectedFile();
            File newDir = new File(file.getParentFile(),
                    file.getName().substring(0, file.getName().lastIndexOf('.')) + "_images");

            JLabel label = new JLabel("", JLabel.CENTER);
            JFrame frame = new JFrame();
            frame.setTitle("Campaign Image Extractor");
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.setSize(400, 75);
            frame.add(label);
            SwingUtil.centerOnScreen(frame);
            frame.setVisible(true);
            Reader r = null;
            OutputStream out = null;
            PackedFile pakfile = null;
            try {
                newDir.mkdirs();

                label.setText("Loading campaign ...");
                pakfile = new PackedFile(file);

                Set<String> files = pakfile.getPaths();
                XStream xstream = new XStream();
                int count = 0;
                for (String filename : files) {
                    count++;
                    if (filename.indexOf("assets") < 0) {
                        continue;
                    }
                    r = pakfile.getFileAsReader(filename);
                    Asset asset = (Asset) xstream.fromXML(r);
                    IOUtils.closeQuietly(r);

                    File newFile = new File(newDir, asset.getName() + ".jpg");
                    label.setText("Extracting image " + count + " of " + files.size() + ": " + newFile);
                    if (newFile.exists()) {
                        newFile.delete();
                    }
                    newFile.createNewFile();
                    out = new FileOutputStream(newFile);
                    FileUtil.copyWithClose(new ByteArrayInputStream(asset.getImage()), out);
                }
                label.setText("Done.");
            } catch (Exception ioe) {
                MapTool.showInformation("AssetExtractor failure", ioe);
            } finally {
                if (pakfile != null)
                    pakfile.close();
                IOUtils.closeQuietly(r);
                IOUtils.closeQuietly(out);
            }
        }
    }.start();
}

From source file:Main.java

/**
 * Displays a {@link JFileChooser} to select a directory.
 *
 * @param title The title of the dialog.
 * @param startDirectory The directory where the dialog is initialed opened.
 * @return The {@link File} selected, returns null if no directory was selected.
 *//*w ww. jav a 2s  .  c  o  m*/
public static File chooseDirectory(String title, String startDirectory) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setDialogTitle(title);

    if (startDirectory != null && !startDirectory.trim().equals("")) {
        chooser.setCurrentDirectory(new File(startDirectory));
    }

    int status = chooser.showOpenDialog(null);

    if (status == JFileChooser.APPROVE_OPTION) {
        return chooser.getSelectedFile();
    }

    return null;
}

From source file:grafix.principal.Comandos.java

static public void cmdSalvarJPEG() {
    ControleRegistro.alertaRegistro();/*from   ww  w  . j  a v a2  s .  c  om*/
    JFileChooser chooser = new JFileChooser();
    chooser.setSelectedFile(new File(".jpg"));
    int returnVal = chooser.showSaveDialog(Controle.getTela());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = chooser.getSelectedFile();
        try {
            ChartUtilities.saveChartAsJPEG(file, Controle.getJanelaAtiva().getPanelGraficos().getChart(),
                    Controle.getJanelaAtiva().getWidth(), Controle.getJanelaAtiva().getHeight());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:lu.lippmann.cdb.ext.hydviga.ui.GapsUIUtil.java

private static void addExportPopupMenu(final Instances ds, final ChartPanel cp) {
    cp.addChartMouseListener(new ChartMouseListener() {
        public void chartMouseClicked(ChartMouseEvent e) {
            final JPopupMenu jPopupMenu = new JPopupMenu("feur");
            final JMenuItem mi1 = new JMenuItem("Export as CSV");
            mi1.addActionListener(new ActionListener() {
                @Override//from w ww . j a  v a2s .  com
                public void actionPerformed(final ActionEvent e) {
                    final JFileChooser fc = new JFileChooser();
                    fc.setAcceptAllFileFilterUsed(false);
                    final int returnVal = fc.showSaveDialog(cp);
                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                        try {
                            final File file = fc.getSelectedFile();
                            WekaDataAccessUtil.saveInstancesIntoCSVFile(ds, file);
                        } catch (final Exception ee) {
                            ee.printStackTrace();
                        }
                    }
                }
            });
            jPopupMenu.add(mi1);
            jPopupMenu.show(cp, e.getTrigger().getX(), e.getTrigger().getY());
        }

        public void chartMouseMoved(ChartMouseEvent e) {
        }
    });
}

From source file:net.sf.jabref.importer.ImportFormats.java

/**
 * Create an AbstractAction for performing an Import operation.
 * @param frame The JabRefFrame of this JabRef instance.
 * @param openInNew Indicate whether the action should open into a new database or
 *  into the currently open one./*from w w  w  .j  a  v a  2 s  . com*/
 * @return The action.
 */
public static AbstractAction getImportAction(JabRefFrame frame, boolean openInNew) {

    class ImportAction extends MnemonicAwareAction {

        private final JabRefFrame frame;
        private final boolean openInNew;

        public ImportAction(JabRefFrame frame, boolean openInNew) {
            this.frame = frame;
            this.openInNew = openInNew;

            putValue(Action.NAME, openInNew ? Localization.menuTitle("Import into new database")
                    : Localization.menuTitle("Import into current database"));
            putValue(Action.ACCELERATOR_KEY,
                    openInNew ? Globals.getKeyPrefs().getKey(KeyBinding.IMPORT_INTO_NEW_DATABASE)
                            : Globals.getKeyPrefs().getKey(KeyBinding.IMPORT_INTO_CURRENT_DATABASE));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = createImportFileChooser(
                    Globals.prefs.get(JabRefPreferences.IMPORT_WORKING_DIRECTORY));
            int result = fileChooser.showOpenDialog(frame);

            if (result != JFileChooser.APPROVE_OPTION) {
                return;
            }

            File file = fileChooser.getSelectedFile();
            if (file == null) {
                return;
            }

            FileFilter ff = fileChooser.getFileFilter();
            ImportFormat format = null;
            if (ff instanceof ImportFileFilter) {
                format = ((ImportFileFilter) ff).getImportFormat();
            }

            try {
                if (!file.exists()) {
                    // Warn that the file doesn't exists:
                    JOptionPane.showMessageDialog(frame,
                            Localization.lang("File not found") + ": '" + file.getName() + "'.",
                            Localization.lang("Import"), JOptionPane.ERROR_MESSAGE);
                    return;
                }
                ImportMenuItem imi = new ImportMenuItem(frame, openInNew, format);
                imi.automatedImport(Collections.singletonList(file.getAbsolutePath()));

                // Make sure we remember which filter was used, to set the default
                // for next time:
                if (format == null) {
                    Globals.prefs.put(JabRefPreferences.LAST_USED_IMPORT, "__all");
                } else {
                    Globals.prefs.put(JabRefPreferences.LAST_USED_IMPORT, format.getFormatName());
                }
                Globals.prefs.put(JabRefPreferences.IMPORT_WORKING_DIRECTORY, file.getParent());
            } catch (Exception ex) {
                LOGGER.warn("Problem with import format", ex);
            }

        }
    }

    return new ImportAction(frame, openInNew);
}

From source file:Main.java

public static File saveImageFile(Component parent) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(new FileFilter() {
        @Override/*from  w w  w .j  a  v a  2 s.co  m*/
        public String getDescription() {
            return "bmp";
        }

        @Override
        public boolean accept(File f) {
            String name = f.getName();
            boolean accepted = f.isDirectory() || name.endsWith(".bmp");
            return accepted;
        }
    });

    fileChooser.showSaveDialog(parent);
    return fileChooser.getSelectedFile();
}