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:modelibra.swing.app.util.FileSelector.java

/**
 * Gets the saved file given a file path.
 * /*from w w w . jav a 2  s  .  co m*/
 * @param path
 *            path
 * @param lang
 *            language
 * @return file
 */
public File getSaveFile(String path, NatLang lang) {
    File selectedFile = null;
    File currentFile = null;
    if (path != null && !path.equalsIgnoreCase("?")) {
        currentFile = new File(path);
    } else
        currentFile = lastSavedFile;

    JFileChooser chooser = new JFileChooser();
    chooser.setLocale(lang.getLocale());
    if (currentFile != null) {
        chooser.setCurrentDirectory(currentFile);
    }
    int returnVal = chooser.showSaveDialog(chooser);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        selectedFile = chooser.getSelectedFile(); // a complete path
        if (selectedFile.exists()) {
            if (!replaceFile(null, lang)) {
                selectedFile = null;
            }
        }
    }
    lastSavedFile = selectedFile;

    return selectedFile;
}

From source file:IHM.FenetreAjoutAffiche.java

private void btnAfficheActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAfficheActionPerformed

    JFileChooser chooser = new JFileChooser(new File("."));

    chooser.setDialogTitle("ouvrir une image");

    int reponse = chooser.showOpenDialog(this);

    boolean etat;

    if (reponse == JFileChooser.APPROVE_OPTION) {

        InputStream input = null;

        f = chooser.getSelectedFile();

        nomAffiche = f.getName();/*from www .  j a v a  2  s  .c o m*/
        nomF = f.getAbsolutePath();

        txtNomPhoto.setText(nomAffiche);

    }

}

From source file:org.pgptool.gui.ui.tools.browsefs.SaveFileChooserDialog.java

public String askUserForFile() {
    JFileChooser ofd = prepareFileChooser();

    boolean userWantsToSelectOtherFile = true;
    File retFile = null;/*from w w  w.  j a v  a 2  s . c  om*/
    while (userWantsToSelectOtherFile) {
        int result = ofd.showSaveDialog(parentWindow);
        if (result != JFileChooser.APPROVE_OPTION) {
            return onDialogClosed(null, ofd);
        }
        retFile = ofd.getSelectedFile();
        if (retFile == null) {
            return onDialogClosed(null, ofd);
        }

        File retFileWithExt = new File(enforceExtension(retFile.getAbsolutePath(), ofd));
        if (userWantsToSelectOtherFile = retFileWithExt.exists()) {
            if (UiUtils.confirm("confirm.overWriteExistingFile",
                    new Object[] { retFileWithExt.getAbsolutePath() }, parentWindow)) {
                userWantsToSelectOtherFile = false;
            }
        }
    }

    Preconditions.checkState(retFile != null, "Useless check but it makes Eclipse NPE checker happier");
    String ret = retFile.getAbsolutePath();
    ret = onDialogClosed(ret, ofd);
    return ret;
}

From source file:com.floreantpos.bo.actions.DataExportAction.java

@Override
public void actionPerformed(ActionEvent e) {
    Session session = null;//w w  w. ja v  a2 s .  co m
    Transaction transaction = null;
    FileWriter fileWriter = null;
    GenericDAO dao = new GenericDAO();

    try {
        JFileChooser fileChooser = getFileChooser();
        int option = fileChooser.showSaveDialog(com.floreantpos.util.POSUtil.getBackOfficeWindow());
        if (option != JFileChooser.APPROVE_OPTION) {
            return;
        }

        File file = fileChooser.getSelectedFile();
        if (file.exists()) {
            option = JOptionPane.showConfirmDialog(com.floreantpos.util.POSUtil.getFocusedWindow(),
                    Messages.getString("DataExportAction.1") + file.getName() + "?", //$NON-NLS-1$//$NON-NLS-2$
                    Messages.getString("DataExportAction.3"), //$NON-NLS-1$
                    JOptionPane.YES_NO_OPTION);
            if (option != JOptionPane.YES_OPTION) {
                return;
            }
        }

        // fixMenuItemModifierGroups();

        JAXBContext jaxbContext = JAXBContext.newInstance(Elements.class);
        Marshaller m = jaxbContext.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

        StringWriter writer = new StringWriter();

        session = dao.createNewSession();
        transaction = session.beginTransaction();

        Elements elements = new Elements();

        //          * 2. USERS
        //          * 3. TAX
        //          * 4. MENU_CATEGORY
        //          * 5. MENU_GROUP
        //          * 6. MENU_MODIFIER
        //          * 7. MENU_MODIFIER_GROUP
        //          * 8. MENU_ITEM
        //          * 9. MENU_ITEM_SHIFT
        //          * 10. RESTAURANT
        //          * 11. USER_TYPE
        //          * 12. USER_PERMISSION
        //          * 13. SHIFT

        elements.setTaxes(TaxDAO.getInstance().findAll(session));
        elements.setMenuCategories(MenuCategoryDAO.getInstance().findAll(session));
        elements.setMenuGroups(MenuGroupDAO.getInstance().findAll(session));
        elements.setMenuModifiers(MenuModifierDAO.getInstance().findAll(session));
        elements.setMenuModifierGroups(MenuModifierGroupDAO.getInstance().findAll(session));
        elements.setMenuItems(MenuItemDAO.getInstance().findAll(session));
        elements.setMenuItemModifierGroups(MenuItemModifierGroupDAO.getInstance().findAll(session));

        //           elements.setUsers(UserDAO.getInstance().findAll(session));
        //           
        //           elements.setMenuItemShifts(MenuItemShiftDAO.getInstance().findAll(session));
        //           elements.setRestaurants(RestaurantDAO.getInstance().findAll(session));
        //           elements.setUserTypes(UserTypeDAO.getInstance().findAll(session));
        //           elements.setUserPermissions(UserPermissionDAO.getInstance().findAll(session));
        //           elements.setShifts(ShiftDAO.getInstance().findAll(session));

        m.marshal(elements, writer);

        transaction.commit();

        fileWriter = new FileWriter(file);
        fileWriter.write(writer.toString());
        fileWriter.close();

        POSMessageDialog.showMessage(com.floreantpos.util.POSUtil.getFocusedWindow(),
                Messages.getString("DataExportAction.4")); //$NON-NLS-1$

    } catch (Exception e1) {
        transaction.rollback();
        PosLog.error(getClass(), e1);
        POSMessageDialog.showMessage(com.floreantpos.util.POSUtil.getFocusedWindow(), e1.getMessage());
    } finally {
        IOUtils.closeQuietly(fileWriter);
        dao.closeSession(session);
    }
}

From source file:com.github.rholder.gradle.ui.DependencyViewerStandalone.java

private void promptForGradleBaseDir() {
    JFileChooser c = new JFileChooser();
    c.setDialogTitle(//from  w w w  .ja  v a  2 s. c o m
            "Pick the top level directory to use when viewing dependencies (in case you have a multi-module project)");
    c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int result = c.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
        gradleBaseDir = c.getSelectedFile().getPath();
    }
}

From source file:net.sf.clichart.main.ChartFrame.java

private void saveChart() {
    JFileChooser chooser = new JFileChooser(".");
    chooser.addChoosableFileFilter(new ExtensionFileFilter(".jpg", "JPEG files"));
    chooser.addChoosableFileFilter(new ExtensionFileFilter(".png", "PNG files"));

    if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
        File outputFile = chooser.getSelectedFile();

        if (outputFile.exists()) {
            int result = JOptionPane.showConfirmDialog(this, "File exists - overwrite?", "File exists",
                    JOptionPane.OK_CANCEL_OPTION);
            if (result != JOptionPane.OK_OPTION) {
                return;
            }/*www  . j  a v  a2 s  . c o m*/
        }

        System.err.println("Saving chart to " + outputFile.getPath());
        try {
            new ChartSaver(m_chart, m_initialWidth, m_initialHeight).saveChart(outputFile);
        } catch (ChartSaverException e) {
            JOptionPane.showMessageDialog(this, "Failed to save chart: " + e.getMessage());
        }
    }
}

From source file:com.ibm.watson.WatsonVRTraining.util.images.PhotoCaptureFrame.java

PhotoCaptureFrame() {
    jp = new JPanel();
    jp.setLayout(new BoxLayout(jp, BoxLayout.Y_AXIS));

    JScrollPane scrollPane = new JScrollPane(jp);
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    scrollPane.setPreferredSize(new Dimension(dim.width / 2 - 40, dim.height - 117));

    JButton btn = new JButton("Upload Image");

    btn.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            JFileChooser fc = new JFileChooser(System.getenv("user.home"));
            fc.setFileFilter(new JPEGImageFileFilter());
            int res = fc.showOpenDialog(null);
            // We have an image!
            try {
                if (res == JFileChooser.APPROVE_OPTION) {
                    File file = fc.getSelectedFile();
                    //SharedResources.sharedCache.getCapturedImageList().add(file);
                    File tmpf_name = File.createTempFile("tmp",
                            "." + FilenameUtils.getExtension(file.getName()));
                    System.out.println("cp " + file.getPath() + " " + AppConstants.vr_process_img_dir_path
                            + File.separator + tmpf_name.getName());
                    new CommandsUtils().executeCommand("bash", "-c", "cp " + file.getPath() + " "
                            + AppConstants.vr_process_img_dir_path + File.separator + tmpf_name.getName());
                }//from   w  w  w.ja v a2s.  c om
            } catch (Exception iOException) {
            }

        }
    });

    ImageRemainingProcessingLabel = new JLabel("REMAINIG IMAGES:0");
    ImageRemainingProcessingLabel.setHorizontalAlignment(SwingConstants.LEFT);
    ImageRemainingProcessingLabel.setFont(new Font("Arial", Font.BOLD, 13));

    ImagebeingProcessedLabel = new JLabel(" PROCESSING IMAGES:0");
    ImagebeingProcessedLabel.setHorizontalAlignment(SwingConstants.LEFT);
    ImagebeingProcessedLabel.setFont(new Font("Arial", Font.BOLD, 13));

    appIDLabel = new JLabel("APP-ID:" + AppConstants.unique_app_id);
    appIDLabel.setHorizontalAlignment(SwingConstants.LEFT);
    appIDLabel.setFont(new Font("Arial", Font.BOLD, 13));

    headerPanel = new JPanel(new FlowLayout());
    headerPanel.add(ImageRemainingProcessingLabel);
    headerPanel.add(ImagebeingProcessedLabel);
    headerPanel.add(btn);
    headerPanel.add(appIDLabel);
    headerPanel.setSize(new Dimension(getWidth(), 10));

    JPanel contentPane = new JPanel();
    contentPane.add(headerPanel);
    contentPane.add(scrollPane);
    f = new JFrame("IBM Watson Visual Prediction Window");
    f.setContentPane(contentPane);
    f.setSize(dim.width / 2 - 30, dim.height - 40);
    f.setLocation(dim.width / 2, 0);
    f.setResizable(false);
    f.setPreferredSize(new Dimension(dim.width / 2 - 30, dim.height - 60));
    f.setVisible(true);
}

From source file:ImageIOTest.java

/**
 * Open a file and load the images.//from   ww w.  ja  v a  2  s  . co  m
 */
public void openFile() {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new File("."));
    String[] extensions = ImageIO.getReaderFileSuffixes();
    chooser.setFileFilter(new FileNameExtensionFilter("Image files", extensions));
    int r = chooser.showOpenDialog(this);
    if (r != JFileChooser.APPROVE_OPTION)
        return;
    File f = chooser.getSelectedFile();
    Box box = Box.createVerticalBox();
    try {
        String name = f.getName();
        String suffix = name.substring(name.lastIndexOf('.') + 1);
        Iterator<ImageReader> iter = ImageIO.getImageReadersBySuffix(suffix);
        ImageReader reader = iter.next();
        ImageInputStream imageIn = ImageIO.createImageInputStream(f);
        reader.setInput(imageIn);
        int count = reader.getNumImages(true);
        images = new BufferedImage[count];
        for (int i = 0; i < count; i++) {
            images[i] = reader.read(i);
            box.add(new JLabel(new ImageIcon(images[i])));
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this, e);
    }
    setContentPane(new JScrollPane(box));
    validate();
}

From source file:it.unibas.spicygui.controllo.mapping.ActionExportTgds.java

@Override
public void performAction() {
    Scenario scenario = (Scenario) modello.getBean(Costanti.CURRENT_SCENARIO);
    MappingTask mappingTask = scenario.getMappingTask();

    JFileChooser chooser = vista.getFileChooserApriTXT();
    File file;/*w  w w.ja  va  2s .c  o m*/
    continua = true;
    while (continua) {
        int returnVal = chooser.showDialog(WindowManager.getDefault().getMainWindow(),
                NbBundle.getMessage(Costanti.class, Costanti.EXPORT_TGDS));
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            file = chooser.getSelectedFile();
            if (!file.exists()) {
                saveTGDs(mappingTask, file);
            } else {
                confirmSave(mappingTask, file);
            }
        } else {
            continua = false;
        }
    }
    /*    List<FORule> foRules = mappingTask.getMappingData().getSTTgds(); 
    for (FORule foRule : foRules) {
    System.out.println(foRule.toLogicalString(mappingTask));
    }*/
}

From source file:edu.umich.robot.GuiApplication.java

/**
 * <p>/* w  ww.j av a2 s .co  m*/
 * Firing up this application requires a configuration file. If no
 * configuration file is presented on the command line, this is called to
 * prompt the user to select a configuration file.
 * 
 * <p>
 * Future work should probably include some default instead of doing this.
 * 
 * @return The selected, loaded configuration file.
 */
public static Config promptForConfig(Component parent) {

    System.out.println("CLASSPATH: " + System.getenv("CLASSPATH"));
    System.out.println("DYLD_LIBRARY_PATH: " + System.getenv("DYLD_LIBRARY_PATH"));
    System.out.println("LD_LIBRARY_PATH: " + System.getenv("LD_LIBRARY_PATH"));
    System.out.println("SOAR_HOME: " + System.getenv("SOAR_HOME"));
    System.out.println("java.library.path: " + System.getProperty("java.library.path"));

    JFileChooser fc = new JFileChooser(System.getProperty("user.dir"));
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    FileFilter filter = new FileNameExtensionFilter("Text Config File", "txt");
    fc.setFileFilter(filter);
    fc.setMultiSelectionEnabled(false);
    int ret = fc.showOpenDialog(parent);
    if (ret == JFileChooser.APPROVE_OPTION) {
        try {
            return new ConfigFile(fc.getSelectedFile().getAbsolutePath());
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }
    return null;
}