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:com.qawaa.gui.EventWebScanGUI.java

/**
 * ??//from   w ww . j  ava2s .  c o  m
 */
private static void setConsoleRight() {
    consoleRight = new JPopupMenu();
    consoleRight.setBorderPainted(true);
    consoleRight.setPopupSize(new Dimension(105, 135));
    JMenuItem clear = new JMenuItem(CONTEXT.getMessage("gobal.right.menu.clear", null, Locale.CHINA),
            KeyEvent.VK_L);
    JMenuItem copy = new JMenuItem(CONTEXT.getMessage("gobal.right.menu.copy", null, Locale.CHINA),
            KeyEvent.VK_C);
    JMenuItem cut = new JMenuItem(CONTEXT.getMessage("gobal.right.menu.cut", null, Locale.CHINA),
            KeyEvent.VK_X);
    JMenuItem font = new JMenuItem(CONTEXT.getMessage("gobal.right.menu.font", null, Locale.CHINA),
            KeyEvent.VK_F);
    JMenuItem choose = new JMenuItem(CONTEXT.getMessage("gobal.right.menu.choose", null, Locale.CHINA),
            KeyEvent.VK_O);
    JMenuItem saveas = new JMenuItem(CONTEXT.getMessage("gobal.right.menu.saveas", null, Locale.CHINA),
            KeyEvent.VK_S);
    consoleRight.add(clear);
    consoleRight.add(copy);
    consoleRight.add(cut);
    consoleRight.add(font);
    consoleRight.add(choose);
    consoleRight.add(saveas);
    clear.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            consolePane.setText("");
            jConsole.clear();
        }
    });
    copy.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (consolePane.getText() != null && !consolePane.getText().trim().isEmpty()) {
                Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
                Transferable tText = new StringSelection(consolePane.getText());
                clip.setContents(tText, null);
            }

        }
    });
    cut.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (consolePane.getText() != null && !consolePane.getText().trim().isEmpty()) {
                Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
                Transferable tText = new StringSelection(consolePane.getText());
                clip.setContents(tText, null);
            }
            consolePane.setText("");
            jConsole.clear();
        }
    });
    saveas.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();
            int option = fileChooser.showSaveDialog(null);
            if (option == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                try {
                    if (file.exists() == false) {
                        file.createNewFile();
                    }
                    FileWriter writer = new FileWriter(file);
                    char[] arry = consolePane.getText().toCharArray();
                    writer.write(arry);
                    writer.flush();
                    writer.close();
                    LOG.info(CONTEXT.getMessage("gobal.right.menu.saveas.success", null, Locale.CHINA));
                } catch (IOException ioe) {
                }
            }
        }
    });
}

From source file:Main.java

/**
 * Opens a file chooser dialog/*  www .  j  a va2s . c o m*/
 * @param chooseAFolder true if the dialog should return a folder, false for a file
 */
public static String chooseFile(JComboBox comboBox, boolean chooseAFolder) {
    JFileChooser chooser = new JFileChooser();
    String path = "";
    String currentDir = "";

    if (comboBox.getSelectedItem() != null) {
        currentDir = comboBox.getSelectedItem().toString();
    }

    // Set whether we want to select a folder instead of a file
    if (chooseAFolder) {
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    }

    chooser.setCurrentDirectory(new File(currentDir));

    // Show open dialog; this method does not return until the dialog is closed
    if (chooser.showOpenDialog(comboBox) == JFileChooser.APPROVE_OPTION) {
        path = chooser.getSelectedFile().getAbsolutePath();
    }

    if (path == null || path.equals("")) {
        return currentDir;
    }
    return path;
}

From source file:Main.java

/**
 * Dialog for choosing file.//  www .j  av a  2 s .co m
 * 
 * @param parent the parent component of the dialog, can be null
 * @return selected file or null if no file is selected
 */
public static File chooseImageFile(Component parent) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileFilter(new FileFilter() {
        @Override
        public String getDescription() {
            return "Supported image files(JPEG, PNG, BMP)";
        }

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

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

From source file:com.stacksync.desktop.util.FileUtil.java

private static File showBrowseDialogDefault(int jFileChooserFileSelectionMode) {
    JFileChooser fc = new JFileChooser();

    fc.setFileSelectionMode(jFileChooserFileSelectionMode);

    if (fc.showDialog(null, "Select") != JFileChooser.APPROVE_OPTION) {
        return null;
    }/*from  w  w w  .j a  v a 2 s.  c  o  m*/

    return fc.getSelectedFile();
}

From source file:net.menthor.editor.v2.util.Util.java

public static File chooseFile(Component parent, String lastPath, String dialogTitle, String fileDescription,
        String fileExtension, boolean checkOverrideFile) throws IOException {
    JFileChooser fileChooser = createChooser(lastPath, checkOverrideFile);
    fileChooser.setDialogTitle(dialogTitle);
    FileNameExtensionFilter filter = new FileNameExtensionFilter(fileDescription, fileExtension);
    fileChooser.addChoosableFileFilter(filter);
    if (SystemUtil.onWindows())
        fileChooser.setFileFilter(filter);
    fileChooser.setAcceptAllFileFilterUsed(false);
    if (fileChooser.showDialog(parent, "Ok") == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        if (!file.getName().endsWith("." + fileExtension)) {
            file = new File(file.getCanonicalFile() + "." + fileExtension);
        } else {//from   w w w.  j  a v  a2 s  . c om
            file = new File(file.getCanonicalFile() + "");
        }
        return file;
    } else {
        return null;
    }
}

From source file:net.menthor.editor.v2.util.Util.java

public static File chooseFile(Component parent, String lastPath, String dialogTitle, String fileDescription,
        String fileExtension, String fileExtension2, boolean checkOverrideFile) throws IOException {
    JFileChooser fileChooser = createChooser(lastPath, checkOverrideFile);
    fileChooser.setDialogTitle(dialogTitle);
    FileNameExtensionFilter filter = new FileNameExtensionFilter(fileDescription, fileExtension,
            fileExtension2);/*from  w  ww.j  a va2s .com*/
    fileChooser.addChoosableFileFilter(filter);
    if (SystemUtil.onWindows())
        fileChooser.setFileFilter(filter);
    fileChooser.setAcceptAllFileFilterUsed(false);
    if (fileChooser.showDialog(parent, "Ok") == JFileChooser.APPROVE_OPTION) {
        File file = fileChooser.getSelectedFile();
        if (!(file.getName().endsWith("." + fileExtension))
                && !(file.getName().endsWith("." + fileExtension2))) {
            file = new File(file.getCanonicalFile() + "." + fileExtension2);
        } else {
            file = new File(file.getCanonicalFile() + "");
        }
        return file;
    } else {
        return null;
    }
}

From source file:net.pms.newgui.Wizard.java

public static void run(final PmsConfiguration configuration) {
    // Total number of questions
    int numberOfQuestions = Platform.isMac() ? 4 : 5;

    // The current question number
    int currentQuestionNumber = 1;

    String status = new StringBuilder().append(Messages.getString("Wizard.2")).append(" %d ")
            .append(Messages.getString("Wizard.4")).append(" ").append(numberOfQuestions).toString();

    Object[] okOptions = { Messages.getString("Dialog.OK") };

    Object[] yesNoOptions = { Messages.getString("Dialog.YES"), Messages.getString("Dialog.NO") };

    Object[] networkTypeOptions = { Messages.getString("Wizard.8"), Messages.getString("Wizard.9"),
            Messages.getString("Wizard.10") };

    if (!Platform.isMac()) {
        // Ask if they want UMS to start minimized
        int whetherToStartMinimized = JOptionPane.showOptionDialog(null, Messages.getString("Wizard.3"),
                String.format(status, currentQuestionNumber++), JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE, null, yesNoOptions, yesNoOptions[1]);

        if (whetherToStartMinimized == JOptionPane.YES_OPTION) {
            configuration.setMinimized(true);
        } else if (whetherToStartMinimized == JOptionPane.NO_OPTION) {
            configuration.setMinimized(false);
        }//w  ww.  j a v a  2 s . co  m
    }

    // Ask if their network is wired, etc.
    int networkType = JOptionPane.showOptionDialog(null, Messages.getString("Wizard.7"),
            String.format(status, currentQuestionNumber++), JOptionPane.YES_NO_CANCEL_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, networkTypeOptions, networkTypeOptions[1]);

    switch (networkType) {
    case JOptionPane.YES_OPTION:
        // Wired (Gigabit)
        configuration.setMaximumBitrate("0");
        configuration.setMPEG2MainSettings("Automatic (Wired)");
        configuration.setx264ConstantRateFactor("Automatic (Wired)");
        break;
    case JOptionPane.NO_OPTION:
        // Wired (100 Megabit)
        configuration.setMaximumBitrate("90");
        configuration.setMPEG2MainSettings("Automatic (Wired)");
        configuration.setx264ConstantRateFactor("Automatic (Wired)");
        break;
    case JOptionPane.CANCEL_OPTION:
        // Wireless
        configuration.setMaximumBitrate("30");
        configuration.setMPEG2MainSettings("Automatic (Wireless)");
        configuration.setx264ConstantRateFactor("Automatic (Wireless)");
        break;
    default:
        break;
    }

    // Ask if they want to hide advanced options
    int whetherToHideAdvancedOptions = JOptionPane.showOptionDialog(null, Messages.getString("Wizard.11"),
            String.format(status, currentQuestionNumber++), JOptionPane.YES_NO_OPTION,
            JOptionPane.QUESTION_MESSAGE, null, yesNoOptions, yesNoOptions[0]);

    if (whetherToHideAdvancedOptions == JOptionPane.YES_OPTION) {
        configuration.setHideAdvancedOptions(true);
    } else if (whetherToHideAdvancedOptions == JOptionPane.NO_OPTION) {
        configuration.setHideAdvancedOptions(false);
    }

    // Ask if they want to scan shared folders
    int whetherToScanSharedFolders = JOptionPane.showOptionDialog(null,
            Messages.getString("Wizard.IsStartupScan"), String.format(status, currentQuestionNumber++),
            JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, yesNoOptions, yesNoOptions[0]);

    if (whetherToScanSharedFolders == JOptionPane.YES_OPTION) {
        configuration.setScanSharedFoldersOnStartup(true);
    } else if (whetherToScanSharedFolders == JOptionPane.NO_OPTION) {
        configuration.setScanSharedFoldersOnStartup(false);
    }

    // Ask to set at least one shared folder
    JOptionPane.showOptionDialog(null, Messages.getString("Wizard.12"),
            String.format(status, currentQuestionNumber++), JOptionPane.OK_OPTION,
            JOptionPane.INFORMATION_MESSAGE, null, okOptions, okOptions[0]);

    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                JFileChooser chooser;
                try {
                    chooser = new JFileChooser();
                } catch (Exception ee) {
                    chooser = new JFileChooser(new RestrictedFileSystemView());
                }

                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                chooser.setDialogTitle(Messages.getString("Wizard.12"));
                chooser.setMultiSelectionEnabled(false);
                if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
                    configuration.setOnlySharedDirectory(chooser.getSelectedFile().getAbsolutePath());
                } else {
                    // If the user cancels this option, the default directories will be used.
                }
            }
        });
    } catch (InterruptedException | InvocationTargetException e) {
        LOGGER.error("Error when saving folders: ", e);
    }

    // The wizard finished, do not ask them again
    configuration.setRunWizard(false);

    // Save all changes
    try {
        configuration.save();
    } catch (ConfigurationException e) {
        LOGGER.error("Error when saving changed configuration: ", e);
    }
}

From source file:SwingUtil.java

/**
 * Get a file selection using the FileChooser dialog.
 *
 * @param owner/*w  w w.  j av  a 2 s  . c  o  m*/
 * The parent of this modal dialog.
 * @param defaultSelection
 * The default file selection as a file.
 * @param filter
 * An extension filter
 * @param title
 * The caption for the dialog.
 *
 * @return
 * A selected file or null if no selection is made.
 */
public static File getFileChoice(Component owner, File defaultSelection, FileFilter filter, String title) {
    //
    // There is apparently a bug in the native Windows FileSystem class that
    // occurs when you use a file chooser and there is a security manager
    // active. An error dialog is displayed indicating there is no disk in
    // Drive A:. To avoid this, the security manager is temporarily set to
    // null and then reset after the file chooser is closed.
    //
    SecurityManager sm = null;
    File choice = null;
    JFileChooser chooser = null;

    sm = System.getSecurityManager();
    System.setSecurityManager(null);

    chooser = new JFileChooser();
    if (defaultSelection.isDirectory()) {
        chooser.setCurrentDirectory(defaultSelection);
    } else {
        chooser.setSelectedFile(defaultSelection);
    }
    chooser.setFileFilter(filter);
    chooser.setDialogTitle(title);
    chooser.setApproveButtonText("OK");
    int v = chooser.showOpenDialog(owner);

    owner.requestFocus();
    switch (v) {
    case JFileChooser.APPROVE_OPTION:
        if (chooser.getSelectedFile() != null) {
            choice = chooser.getSelectedFile();
        }
        break;
    case JFileChooser.CANCEL_OPTION:
    case JFileChooser.ERROR_OPTION:
    }
    chooser.removeAll();
    chooser = null;
    System.setSecurityManager(sm);
    return choice;
}

From source file:at.tuwien.ifs.somtoolbox.apps.viewer.fileutils.ExportUtils.java

public static void saveMapPaneAsImage(Container container, JFileChooser fileChooser,
        GenericPNodeScrollPane mapPane, String title) {
    JFileChooser fc = ExportUtils.getFileChooser(container, fileChooser, new JCheckBox("Crop", true));
    int returnVal = fc.showDialog(container, title);
    File filePath = null;/*from   ww w.  j av a 2  s.  c  o m*/

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        filePath = fc.getSelectedFile();
    }
    if (filePath != null) {
        try {
            ExportUtils.saveMapPaneAsImage(mapPane, filePath.getAbsolutePath(),
                    ((JCheckBox) fc.getAccessory()).isSelected());
            JOptionPane.showMessageDialog(container, "Export to file finished!");
        } catch (SOMToolboxException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(container, ex.getMessage(), "Error saving",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:SwingUtil.java

/**
 * Open a JFileChooser dialog for selecting a directory and return the
 * selected directory.// ww w  .  j  a v  a  2  s  .co m
 *
 *
 * @param owner
 * The frame or dialog that controls the invokation of this dialog.
 * @param defaultDir
 * The directory to show when the dialog opens.
 * @param title
 * Tile for the dialog.
 *
 * @return
 * The selected directory as a File. Null if user cancels dialog without
 * a selection.
 *
 */
public static File getDirectoryChoice(Component owner, File defaultDir, String title) {
    //
    // There is apparently a bug in the native Windows FileSystem class that
    // occurs when you use a file chooser and there is a security manager
    // active. An error dialog is displayed indicating there is no disk in
    // Drive A:. To avoid this, the security manager is temporarily set to
    // null and then reset after the file chooser is closed.
    //
    SecurityManager sm = null;
    JFileChooser chooser = null;
    File choice = null;

    sm = System.getSecurityManager();
    System.setSecurityManager(null);
    chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    if ((defaultDir != null) && defaultDir.exists() && defaultDir.isDirectory()) {
        chooser.setCurrentDirectory(defaultDir);
        chooser.setSelectedFile(defaultDir);
    }
    chooser.setDialogTitle(title);
    chooser.setApproveButtonText("OK");
    int v = chooser.showOpenDialog(owner);

    owner.requestFocus();
    switch (v) {
    case JFileChooser.APPROVE_OPTION:
        if (chooser.getSelectedFile() != null) {
            if (chooser.getSelectedFile().exists()) {
                choice = chooser.getSelectedFile();
            } else {
                File parentFile = new File(chooser.getSelectedFile().getParent());

                choice = parentFile;
            }
        }
        break;
    case JFileChooser.CANCEL_OPTION:
    case JFileChooser.ERROR_OPTION:
    }
    chooser.removeAll();
    chooser = null;
    System.setSecurityManager(sm);
    return choice;
}