Example usage for javax.swing JFileChooser setFileSelectionMode

List of usage examples for javax.swing JFileChooser setFileSelectionMode

Introduction

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

Prototype

@BeanProperty(preferred = true, enumerationValues = { "JFileChooser.FILES_ONLY",
        "JFileChooser.DIRECTORIES_ONLY",
        "JFileChooser.FILES_AND_DIRECTORIES" }, description = "Sets the types of files that the JFileChooser can choose.")
public void setFileSelectionMode(int mode) 

Source Link

Document

Sets the JFileChooser to allow the user to just select files, just select directories, or select both files and directories.

Usage

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//from  w ww .  j  av a2s .  c  o  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: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;/* w ww  .  jav 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: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   w ww  .java2  s .com
    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

/**
 * Opens a file chooser dialog//from   w w w  .j ava2s.c om
 * @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:com.mgmtp.jfunk.core.JFunk.java

private static List<File> requestScriptsViaGui() {
    final List<File> scripts = new ArrayList<>();

    try {//from  ww w.  ja va2 s  .  c o  m
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                JFileChooser fileChooser = new JFileChooser(System.getProperty(JFunkConstants.USER_DIR));
                fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                fileChooser.setMultiSelectionEnabled(true);
                fileChooser.setPreferredSize(new Dimension(800, 450));
                int i = fileChooser.showOpenDialog(null);

                if (i == JFileChooser.APPROVE_OPTION) {
                    File[] files = fileChooser.getSelectedFiles();
                    scripts.addAll(Arrays.asList(files));
                }
            }
        });
    } catch (Exception e) {
        LOG.error("Error while requesting scripts via GUI", e);
    }

    return scripts;
}

From source file:SwingUtil.java

/**
 * Open a JFileChooser dialog for selecting a directory and return the
 * selected directory./*from   w w w  . j  ava  2s .c  om*/
 *
 *
 * @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;
}

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);
        }/*ww w . ja  va  2 s .  c  o 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: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 ww w. j  a v  a2s. co  m*/

    return fc.getSelectedFile();
}

From source file:marytts.tools.voiceimport.DatabaseImportMain.java

private static File determineVoiceBuildingDir(String[] args) {
    // Determine the voice building directory in the following order:
    // 1. System property "user.dir"
    // 2. First command line argument
    // 3. current directory
    // 4. Prompt user via gui.
    // Do a sanity check -- do they exist, do they have a wav/ subdirectory?

    String voiceBuildingDir = null;
    Vector<String> candidates = new Vector<String>();
    candidates.add(System.getProperty("user.dir"));
    if (args.length > 0)
        candidates.add(args[0]);/*from   w w  w  .  jav  a2 s . com*/
    candidates.add("."); // current directory
    for (String dir : candidates) {
        if (dir != null && new File(dir).isDirectory() && new File(dir + "/wav").isDirectory()) {
            voiceBuildingDir = dir;
            break;
        }
    }
    if (voiceBuildingDir == null) { // need to ask user
        JFrame window = new JFrame("This is the Frames's Title Bar!");
        JFileChooser fc = new JFileChooser();
        fc.setDialogTitle("Choose Voice Building Directory");
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        System.out.println("Opening GUI....... ");
        //outDir.setText(file.getAbsolutePath());
        //System.exit(0);
        int returnVal = fc.showOpenDialog(window);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            if (file != null)
                voiceBuildingDir = file.getAbsolutePath();
        }
    }
    System.setProperty("user.dir", voiceBuildingDir);
    if (voiceBuildingDir != null) {
        return new File(voiceBuildingDir);
    } else {
        return null;
    }
}

From source file:lectorarchivos.VerCSV.java

public static String abrirSelectorXML() throws IOException {
    JFileChooser selector = new JFileChooser();
    FileNameExtensionFilter filtroArchivo = new FileNameExtensionFilter("csv & xls & txt", "csv", "xls", "txt");
    selector.setFileFilter(filtroArchivo);
    selector.setFileSelectionMode(JFileChooser.FILES_ONLY);
    selector.setMultiSelectionEnabled(false);

    //int r=selector.showOpenDialog(this);

    /*if(r==JFileChooser.APPROVE_OPTION){
    //Recorremos el array de ficheros seleccionados
    rutaFichero = selector.getSelectedFile().toPath().toAbsolutePath().toString(); 
    }else{//from  ww  w  . j a  va 2 s.c o  m
    System.out.println("Yo devuelvo nullo");
    }*/
    return rutaFichero;
}