Example usage for javax.swing JFileChooser showOpenDialog

List of usage examples for javax.swing JFileChooser showOpenDialog

Introduction

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

Prototype

public int showOpenDialog(Component parent) throws HeadlessException 

Source Link

Document

Pops up an "Open File" file chooser dialog.

Usage

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 ww  w  . java 2  s. co  m*/
 * @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:my.grafos.Maquina.java

static void abrirGrafo() throws FileNotFoundException, IOException, ClassNotFoundException {
    /*       FileInputStream fis = new FileInputStream("d:\\t.xml");
    ObjectInputStream ois = new ObjectInputStream(fis);
    ArrayList<Aresta> leituraListaistaArestas = (ArrayList<Aresta>) ois.readObject();
    ois.close();/*ww w .j av a 2s .c  o m*/
    Fabrica.listaArestas = leituraListaistaArestas;
     */

    a = 0;
    final JFileChooser fc = new JFileChooser();
    //Handle open button action.
    int returnVal = fc.showOpenDialog(null);
    File file = fc.getSelectedFile();
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        file = fc.getSelectedFile();
        //This is where a real application would open the file.
        System.out.println("Opening: " + file.getName() + "." + "\n");

    } else {
        System.out.println("Open command cancelled by user." + "\n");
    }
    StringBuilder arestaBuilder = new StringBuilder();
    StringBuilder verticeBuilder = new StringBuilder();
    String line;
    try {
        InputStream inputstream = new BufferedInputStream(new FileInputStream(file.getPath()));
        BufferedReader r = new BufferedReader(new InputStreamReader(inputstream));
        while ((line = r.readLine()) != null && !line.contains("</list>")) {
            arestaBuilder.append(line);
            arestaBuilder.append("\n");
        }
        arestaBuilder.append("</list>");
        verticeBuilder.append("<list>\n");

        while ((line = r.readLine()) != null) {
            verticeBuilder.append(line);
            verticeBuilder.append("\n");
        }
    } catch (IOException e) {
    }
    Fabrica.xmlA = arestaBuilder.toString();
    Fabrica.xmlV = verticeBuilder.toString();
    Fabrica.listaArestas = (ArrayList<Aresta>) xstream.fromXML(xmlA);
    Fabrica.listaVertices = (ArrayList<Vertice>) xstream.fromXML(xmlV);
}

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.
 *//*from   w  w w.  j  a  v a 2 s  .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:com.rpgsheet.xcom.PimpMyXcom.java

private static void openXcomPathDialog(Properties appProperties) {
    // display the box to the user
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("PimpMyXcom - Where is X-COM?");
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int retCode = fileChooser.showOpenDialog(null);
    // if the user cancelled the dialog, there is nothing we can do
    if (retCode == JFileChooser.CANCEL_OPTION) {
        log.error("User cancel while attempting to locate X-COM.");
        return;/*from w w  w  .  j  a  v  a 2s.  c o  m*/
    }
    // if there was an error, there is nothing we can do
    if (retCode == JFileChooser.ERROR_OPTION) {
        log.error("Error while attempting to locate X-COM: {}", JFileChooser.ERROR_OPTION);
        return;
    }
    // if the user chose a directory, then we have some work to do
    String xcomPath = fileChooser.getSelectedFile().getAbsolutePath();
    File xcomDir = new File(xcomPath);
    if (containsXcom(xcomDir)) {
        // store the path to xcom in the application properties
        appProperties.setProperty("xcom.path", xcomPath);
        // write the updated application properties to disk
        try {
            saveApplicationProperties(appProperties);
        } catch (IOException e) {
            log.error("Unable to store X-COM path in application properties.", e);
            return;
        }
    }
    // if we were unable to find X-COM
    else {
        log.error("User provided location did not contain X-COM.");
        return;
    }
}

From source file:kindleclippings.quizlet.QuizletSync.java

private static Map<String, List<Clipping>> readClippingsFile() throws IOException {
    // try to find it
    File cl = new File("/Volumes/Kindle/documents/My Clippings.txt");
    if (!cl.canRead()) {
        JFileChooser fc = new JFileChooser();
        fc.setFileFilter(new FileNameExtensionFilter("Kindle Clippings", "txt"));
        int result = fc.showOpenDialog(null);
        if (result != JFileChooser.APPROVE_OPTION) {
            return null;
        }/*from  ww  w  .  j  av  a  2s .c om*/
        cl = fc.getSelectedFile();
    }
    Reader f = new InputStreamReader(new FileInputStream(cl), "UTF-8");
    try {
        MyClippingsReader r = new MyClippingsReader(f);

        Map<String, List<Clipping>> books = new TreeMap<String, List<Clipping>>();

        Clipping l;
        while ((l = r.readClipping()) != null) {
            if (l.getType() != ClippingType.highlight && l.getType() != ClippingType.note) {
                System.err.println("ignored " + l.getType() + " [" + l.getBook() + "]");
                continue;
            }
            String lct = l.getContent().trim();
            if (lct.length() == 0) {
                System.err.println("ignored empty " + l.getType() + " [" + l.getBook() + "]");
                continue;
            }
            if (lct.length() < 10 || !lct.contains(" ")) {
                System.err.println(
                        "ignored too short " + l.getType() + " " + l.getContent() + " [" + l.getBook() + "]");
                continue;
            }
            List<Clipping> clippings = books.get(l.getBook());
            if (clippings == null) {
                clippings = new ArrayList<Clipping>();
                books.put(l.getBook(), clippings);
            }
            clippings.add(l);
        }
        return books;
    } finally {
        f.close();
    }
}

From source file:com.stam.batchmove.BatchMoveUtils.java

public static void showFilesFrame(Object[][] data, String[] columnNames, final JFrame callerFrame) {
    final FilesFrame filesFrame = new FilesFrame();

    DefaultTableModel model = new DefaultTableModel(data, columnNames) {

        private static final long serialVersionUID = 1L;

        @Override// w ww.j av a 2s  .  co  m
        public Class<?> getColumnClass(int column) {
            return getValueAt(0, column).getClass();
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return column == 0;
        }
    };
    DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
    renderer.setHorizontalAlignment(JLabel.CENTER);
    final JTable table = new JTable(model);
    for (int i = 1; i < table.getColumnCount(); i++) {
        table.setDefaultRenderer(table.getColumnClass(i), renderer);
    }
    //            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setRowHeight(30);
    table.getTableHeader().setFont(new Font("Serif", Font.BOLD, 14));
    table.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
    table.setRowSelectionAllowed(false);
    table.getColumnModel().getColumn(0).setMaxWidth(35);
    table.getColumnModel().getColumn(1).setPreferredWidth(350);
    table.getColumnModel().getColumn(2).setPreferredWidth(90);
    table.getColumnModel().getColumn(2).setMaxWidth(140);
    table.getColumnModel().getColumn(3).setMaxWidth(90);

    JPanel tblPanel = new JPanel();
    JPanel btnPanel = new JPanel();

    tblPanel.setLayout(new BorderLayout());
    if (table.getRowCount() > 15) {
        JScrollPane scrollPane = new JScrollPane(table);
        tblPanel.add(scrollPane, BorderLayout.CENTER);
    } else {
        tblPanel.add(table.getTableHeader(), BorderLayout.NORTH);
        tblPanel.add(table, BorderLayout.CENTER);
    }

    btnPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

    filesFrame.setMinimumSize(new Dimension(800, 600));
    filesFrame.setLayout(new BorderLayout());
    filesFrame.add(tblPanel, BorderLayout.NORTH);
    filesFrame.add(btnPanel, BorderLayout.SOUTH);

    final JLabel resultsLabel = new JLabel();

    JButton cancelBtn = new JButton("Cancel");
    cancelBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            filesFrame.setVisible(false);
            callerFrame.setVisible(true);
        }
    });

    JButton moveBtn = new JButton("Copy");
    moveBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            fileChooser.setDialogTitle("Choose target directory");
            int selVal = fileChooser.showOpenDialog(null);
            if (selVal == JFileChooser.APPROVE_OPTION) {
                File selection = fileChooser.getSelectedFile();
                String targetPath = selection.getAbsolutePath();

                DefaultTableModel dtm = (DefaultTableModel) table.getModel();
                int nRow = dtm.getRowCount();
                int copied = 0;
                for (int i = 0; i < nRow; i++) {
                    Boolean selected = (Boolean) dtm.getValueAt(i, 0);
                    String filePath = dtm.getValueAt(i, 1).toString();

                    if (selected) {
                        try {
                            FileUtils.copyFileToDirectory(new File(filePath), new File(targetPath));
                            dtm.setValueAt("Copied", i, 3);
                            copied++;
                        } catch (Exception ex) {
                            Logger.getLogger(SelectionFrame.class.getName()).log(Level.SEVERE, null, ex);
                            dtm.setValueAt("Failed", i, 3);
                        }
                    }
                }
                resultsLabel.setText(copied + " files copied. Finished!");
            }
        }
    });
    btnPanel.add(cancelBtn);
    btnPanel.add(moveBtn);
    btnPanel.add(resultsLabel);

    filesFrame.revalidate();
    filesFrame.setVisible(true);

    callerFrame.setVisible(false);
}

From source file:Main.java

/**
 * Creates a new JFileChooser and returns the selected path's location.
 * @param title/*from www  . j a  va2  s .  c o  m*/
 * @param openTo
 * @param chooseDirectory
 * @param filter
 * @return
 */
public static String getFilePath(String title, String openTo, boolean chooseDirectory, FileFilter filter) {
    String location = null;
    JFileChooser chooser = new JFileChooser(title);
    chooser.setCurrentDirectory(new File(openTo));
    chooser.setFileFilter(filter);
    chooser.setDialogTitle("Open Cache");
    if (chooseDirectory) {
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    } else {
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    }
    chooser.setAcceptAllFileFilterUsed(false);
    if (chooser.showOpenDialog(chooser) == JFileChooser.APPROVE_OPTION) {
        location = chooser.getSelectedFile().getAbsolutePath();
    }
    return location;
}

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//w w  w . j  av  a2  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:de.dakror.virtualhub.server.dialog.BackupEditDialog.java

public static void show() throws JSONException {
    final JDialog dialog = new JDialog(Server.currentServer.frame, "Backup-Einstellungen", true);
    dialog.setSize(400, 250);//from  ww w .j a  v a  2 s.c o  m
    dialog.setLocationRelativeTo(Server.currentServer.frame);
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);

    JPanel cp = new JPanel(new SpringLayout());
    cp.add(new JLabel("Zielverzeichnis:"));
    JPanel panel = new JPanel();
    final JTextField path = new JTextField((Server.currentServer.settings.has("backup.path")
            ? Server.currentServer.settings.getString("backup.path")
            : ""), 10);
    panel.add(path);
    panel.add(new JButton(new AbstractAction("Whlen...") {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser jfc = new JFileChooser((path.getText().length() > 0 ? new File(path.getText())
                    : new File(System.getProperty("user.home"))));
            jfc.setFileHidingEnabled(false);
            jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            jfc.setDialogTitle("Backup-Zielverzeichnis whlen");

            if (jfc.showOpenDialog(dialog) == JFileChooser.APPROVE_OPTION)
                path.setText(jfc.getSelectedFile().getPath().replace("\\", "/"));
        }
    }));

    cp.add(panel);

    cp.add(new JLabel(""));
    cp.add(new JLabel(""));

    cp.add(new JButton(new AbstractAction("Abbrechen") {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.dispose();
        }
    }));
    cp.add(new JButton(new AbstractAction("Speichern") {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                if (path.getText().length() > 0)
                    Server.currentServer.settings.put("backup.path", path.getText());
                dialog.dispose();
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
        }
    }));

    SpringUtilities.makeCompactGrid(cp, 3, 2, 6, 6, 6, 6);
    dialog.setContentPane(cp);
    dialog.pack();
    dialog.setVisible(true);
}

From source file:Main.java

/**
 * Consistent way to chosing a file to open with JFileChooser.
 * <p>/*from w  w w. ja  va2 s  .c  o  m*/
 * 
 * @see JFileChooser#setFileSelectionMode(int)
 * @see #getSystemFiles(Component, int)
 * @param owner to show the component relative to.
 * @param mode selection mode for the JFileChooser.
 * @return File based on the user selection can be null.
 */
public static File getSystemFile(Component owner, int mode, FileFilter[] filters) {

    JFileChooser jfc = new JFileChooser();
    jfc.setFileSelectionMode(mode);
    jfc.setFileHidingEnabled(true);
    jfc.setAcceptAllFileFilterUsed(true);
    if (filters != null) {
        for (int i = 0; i < filters.length; i++) {
            jfc.addChoosableFileFilter(filters[i]);
        }

        if (filters.length >= 1) {
            jfc.setFileFilter(filters[0]);
        }
    }

    int result = jfc.showOpenDialog(owner);

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

    return null;
}