Example usage for javax.swing JFileChooser getSelectedFiles

List of usage examples for javax.swing JFileChooser getSelectedFiles

Introduction

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

Prototype

public File[] getSelectedFiles() 

Source Link

Document

Returns a list of selected files if the file chooser is set to allow multiple selection.

Usage

From source file:org.pentaho.support.standalone.SDSupportUtility.java

/**
 * initializing UI// ww w  .  j a va2s  .  co  m
 * 
 * @throws Exception
 */
public SDSupportUtility() throws Exception {

    prop = loadProperty();

    setResizable(false);
    setTitle(SDConstant.PENT_SUP_WIZARD);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 665, 516);

    contentPane = new JPanel();
    contentPane.setBackground(UIManager.getColor("Button.background"));
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JLabel lblLastAttached = new JLabel("Last Attached");
    lblLastAttached.setOpaque(false);
    lblLastAttached.setHorizontalAlignment(SwingConstants.LEFT);
    lblLastAttached.setBounds(322, 335, 127, 23);
    contentPane.add(lblLastAttached);

    JLabel lblPentahoCustomerSupport = new JLabel("Pentaho Customer Support Wizard");
    lblPentahoCustomerSupport.setForeground(new Color(51, 51, 51));
    lblPentahoCustomerSupport.setVerticalAlignment(SwingConstants.TOP);
    lblPentahoCustomerSupport.setHorizontalAlignment(SwingConstants.RIGHT);
    lblPentahoCustomerSupport.setFont(new Font("Tahoma", Font.BOLD, 23));
    lblPentahoCustomerSupport.setBounds(130, 109, 506, 37);
    contentPane.add(lblPentahoCustomerSupport);

    JLabel lbllogo = new JLabel();
    lbllogo.setIcon(new ImageIcon(
            SDSupportUtility.class.getResource("/org/pentaho/support/standalone/puc-login-logo.png")));
    lbllogo.setBounds(10, 11, 409, 93);
    contentPane.add(lbllogo);

    chckbxNewCheckBoxEnvironment = new JCheckBox("Environment");
    chckbxNewCheckBoxEnvironment.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {

            if (e.getStateChange() == ItemEvent.SELECTED) {
                ArgList.add(SDConstant.ENVIRONMENT);
            } else {
                ArgList.remove(SDConstant.ENVIRONMENT);
            }
        }
    });
    chckbxNewCheckBoxEnvironment.setBounds(109, 268, 243, 23);
    contentPane.add(chckbxNewCheckBoxEnvironment);
    chckbxNewCheckBoxEnvironment.setOpaque(false);

    chckbxNewCheckBoxStructure = new JCheckBox("Structure Details");
    chckbxNewCheckBoxStructure.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {

            if (e.getStateChange() == ItemEvent.SELECTED) {
                ArgList.add(SDConstant.STRUCT);
            } else {
                ArgList.remove(SDConstant.STRUCT);
            }
        }
    });
    chckbxNewCheckBoxStructure.setBounds(377, 190, 248, 23);
    contentPane.add(chckbxNewCheckBoxStructure);
    chckbxNewCheckBoxStructure.setOpaque(false);

    chckbxLogs = new JCheckBox("Logs");
    chckbxLogs.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {

            if (e.getStateChange() == ItemEvent.SELECTED) {
                ArgList.add(SDConstant.LOGS);
            } else {
                ArgList.remove(SDConstant.LOGS);
            }
        }
    });
    chckbxLogs.setBounds(377, 164, 248, 23);
    contentPane.add(chckbxLogs);
    chckbxLogs.setOpaque(false);

    chckbxGetSecureFiles = new JCheckBox("Secure Files");
    chckbxGetSecureFiles.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {

            if (e.getStateChange() == ItemEvent.SELECTED) {
                ArgList.add(SDConstant.SECURITY);
            } else {
                ArgList.remove(SDConstant.SECURITY);
            }
        }
    });
    chckbxGetSecureFiles.setBounds(109, 190, 243, 23);
    contentPane.add(chckbxGetSecureFiles);
    chckbxGetSecureFiles.setOpaque(false);

    chckbxMd5 = new JCheckBox("MD5 Hash Value");
    chckbxMd5.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {

            if (e.getStateChange() == ItemEvent.SELECTED) {
                ArgList.add(SDConstant.MD5);
            } else {
                ArgList.remove(SDConstant.MD5);
            }
        }
    });
    chckbxMd5.setBounds(109, 216, 243, 23);
    contentPane.add(chckbxMd5);
    chckbxMd5.setOpaque(false);

    chckbxDbdetails = new JCheckBox("Datasource Details");
    chckbxDbdetails.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {

            if (e.getStateChange() == ItemEvent.SELECTED) {
                ArgList.add(SDConstant.DATASOURCE);
            } else {
                ArgList.remove(SDConstant.DATASOURCE);
            }
        }
    });
    chckbxDbdetails.setBounds(109, 294, 243, 23);
    contentPane.add(chckbxDbdetails);
    chckbxDbdetails.setOpaque(false);

    chckbxLicense = new JCheckBox("License File");
    chckbxLicense.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                ArgList.add(SDConstant.LICENSE);
            } else {
                ArgList.remove(SDConstant.LICENSE);
            }
        }
    });
    chckbxLicense.setBounds(109, 164, 243, 23);
    contentPane.add(chckbxLicense);
    chckbxLicense.setOpaque(false);

    chckbxProcesslist = new JCheckBox("Running Process");
    chckbxProcesslist.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {

            if (e.getStateChange() == ItemEvent.SELECTED) {
                ArgList.add(SDConstant.RUNNING_TASK);
            } else {
                ArgList.remove(SDConstant.RUNNING_TASK);
            }
        }
    });
    chckbxProcesslist.setBounds(109, 242, 243, 23);
    contentPane.add(chckbxProcesslist);
    chckbxProcesslist.setOpaque(false);

    chckbxTomcatxml = new JCheckBox("XML files from Tomcat");
    chckbxTomcatxml.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {

            if (e.getStateChange() == ItemEvent.SELECTED) {
                ArgList.add(SDConstant.FILE);
                tomcatXml = true;
            } else {
                ArgList.remove(SDConstant.FILE);
                tomcatXml = false;
            }
        }
    });
    chckbxTomcatxml.setBounds(377, 242, 248, 23);
    contentPane.add(chckbxTomcatxml);
    chckbxTomcatxml.setOpaque(false);

    chckbxServerXml = new JCheckBox("XML files from Server");
    chckbxServerXml.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {

            if (e.getStateChange() == ItemEvent.SELECTED) {
                ArgList.add(SDConstant.FILE);
                serverXml = true;
            } else {
                ArgList.remove(SDConstant.FILE);
                serverXml = false;
            }
        }
    });
    chckbxServerXml.setBounds(377, 216, 248, 23);
    contentPane.add(chckbxServerXml);
    chckbxServerXml.setOpaque(false);

    chckbxGetBatfiles = new JCheckBox("Start up files from server");
    chckbxGetBatfiles.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {

            if (e.getStateChange() == ItemEvent.SELECTED) {
                ArgList.add(SDConstant.FILE);
                serverBatFile = true;
            } else {
                ArgList.remove(SDConstant.FILE);
                serverBatFile = false;
            }
        }
    });
    chckbxGetBatfiles.setBounds(377, 268, 248, 23);
    contentPane.add(chckbxGetBatfiles);
    chckbxGetBatfiles.setOpaque(false);

    chckbxServerproperties = new JCheckBox("Properites files from server");
    chckbxServerproperties.addItemListener(new ItemListener() {

        public void itemStateChanged(ItemEvent e) {

            if (e.getStateChange() == ItemEvent.SELECTED) {
                ArgList.add(SDConstant.FILE);
                serverProrperties = true;
            } else {
                ArgList.remove(SDConstant.FILE);
                serverProrperties = false;
            }
        }
    });
    chckbxServerproperties.setBounds(377, 294, 248, 23);
    contentPane.add(chckbxServerproperties);
    chckbxServerproperties.setOpaque(false);

    btnNewButton = new JButton("Package");
    btnNewButton.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {

            try {

                if (installType.equalsIgnoreCase("Manual")) {

                    if (prop.getProperty(SDConstant.BI_TOM_PATH) == null) {
                        JOptionPane.showMessageDialog(contentPane, SDConstant.ERROR_12, "Inane error",
                                JOptionPane.ERROR_MESSAGE);
                    } else {

                        WEB_XML = new StringBuilder();
                        WEB_XML.append(prop.getProperty(SDConstant.BI_TOM_PATH)).append(File.separator)
                                .append(SDConstant.WEB_APP).append(File.separator).append(SDConstant.PENTAHO)
                                .append(File.separator).append(SDConstant.WEB_INF).append(File.separator)
                                .append(SDConstant.WEB_XML);

                        PENTAHO_SOLU_PATH = getSolutionPath("biserver", WEB_XML.toString());
                        prop.put(SDConstant.PENTAHO_SOLU_PATH, PENTAHO_SOLU_PATH);
                        prop.put(SDConstant.BI_PATH, PENTAHO_SOLU_PATH);
                    }

                }

                if (prop.getProperty(SDConstant.BI_PATH) == null) {
                    JOptionPane.showMessageDialog(contentPane, SDConstant.ERROR_1, "Inane error",
                            JOptionPane.ERROR_MESSAGE);
                }
                if (prop.getProperty(SDConstant.BI_TOM_PATH) == null) {
                    JOptionPane.showMessageDialog(contentPane, SDConstant.ERROR_12, "Inane error",
                            JOptionPane.ERROR_MESSAGE);
                }
                disableAll();
                setBIServerPath(prop);
                final String data = textFieldBrowser.getText();
                if (!data.equalsIgnoreCase(null)) {
                    ArgList.add(SDConstant.BROWSER);
                }

                String[] array = new String[ArgList.size()];

                int count = 0;
                for (int i = 0; i < ArgList.size(); i++) {

                    String retName = ArgList.get(i);
                    if (retName.equals("file")) {
                        if (count == 0) {
                            array[i] = retName;
                            count++;
                        }
                    } else {
                        array[i] = retName;
                    }

                }

                ApplicationContext context = new ClassPathXmlApplicationContext(SDConstant.SPRNG_FILE_NAME);

                factory = (CofingRetrieverFactory) context.getBean("cofingRetrieverFactory");
                ConfigRetreiver[] config = factory.getConfigRetrevier(array);

                ExecutorService service = Executors.newFixedThreadPool(10);

                for (final ConfigRetreiver configobj : config) {
                    if (null != configobj) {
                        configobj.setBISeverPath(prop);
                        configobj.setServerName("biserver");

                        if (installType.equalsIgnoreCase("Installer")) {
                            configobj.setInstallType("Installer");
                        } else if (installType.equalsIgnoreCase("Archive")) {
                            configobj.setInstallType("Archive");
                        } else if (installType.equalsIgnoreCase("Manual")) {
                            configobj.setInstallType("Manual");
                        }

                        if (configobj instanceof FileRetriever) {
                            configobj.setBidiXml(serverXml);
                            configobj.setBidiBatFile(serverBatFile);
                            configobj.setBidiProrperties(serverProrperties);
                            configobj.setTomcatXml(tomcatXml);
                        }
                        if (configobj instanceof BrowserInfoRetriever) {
                            configobj.setBrowserInfo(data);
                        }

                        service.execute(new Runnable() {
                            public void run() {
                                if (null != configobj)
                                    configobj.readAndSaveConfiguration(prop);
                            }
                        });
                    }
                }
                btnNewButton.setVisible(false);
                progressBar.setVisible(true);
                ProgressThread thread = new ProgressThread();
                thread.setSupport(getSupport());
                thread.setProp(prop);
                new Thread(thread).start();

                service.shutdown();
            } catch (Exception e1) {
                e1.printStackTrace();
            }

        }

    });

    chckbxSelectAll = new JCheckBox("Select/ De-select");
    chckbxSelectAll.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                selectAll();
            } else {
                deSelectAll();
            }
        }
    });

    chckbxSelectAll.setBounds(46, 138, 201, 23);
    chckbxSelectAll.setOpaque(false);
    contentPane.add(chckbxSelectAll);
    btnNewButton.setForeground(SystemColor.infoText);
    btnNewButton.setBounds(10, 430, 639, 37);
    contentPane.add(btnNewButton);
    chckbxServerproperties.setOpaque(false);

    JLabel lblAttach = new JLabel("Attach Artifact");
    lblAttach.setHorizontalAlignment(SwingConstants.LEFT);
    lblAttach.setBounds(32, 335, 177, 23);
    contentPane.add(lblAttach);
    lblAttach.setOpaque(false);

    JButton btnNewButtonBrowse = new JButton("Browse");
    btnNewButtonBrowse.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent arg0) {
            saveSelectedFile(prop);

            JFrame parentFrame = new JFrame();
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("Specify a file to save");
            fileChooser.setMultiSelectionEnabled(true);

            int userSelection = fileChooser.showSaveDialog(parentFrame);

            if (userSelection == JFileChooser.APPROVE_OPTION) {
                fileToSave = fileChooser.getSelectedFiles();
                for (int i = 0; i < fileToSave.length; i++) {
                    File file = fileToSave[i];
                    String artifactpath = file.getAbsolutePath();

                    File f = new File(artifactpath);
                    String absolutefilename = f.getName();
                    String filename = ArtifactsDirectory.concat(absolutefilename);
                    CopyFile artifactcopy = new CopyFile(artifactpath, filename);
                    try {
                        artifactcopy.copy();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }

                }
                uploadedFiles();

                rowList = new JList(model);
                listScrollPane.setViewportView(rowList);
                panel.add(listScrollPane);

            }
            rowList.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    lblDelete.setVisible(true);
                }
            });

        }
    });
    btnNewButtonBrowse.setBounds(208, 335, 104, 23);
    contentPane.add(btnNewButtonBrowse);
    btnNewButtonBrowse.setOpaque(false);

    textFieldBrowser = new JTextField();
    textFieldBrowser.setBounds(208, 364, 441, 23);
    contentPane.add(textFieldBrowser);
    textFieldBrowser.setColumns(10);

    progressBar = new JProgressBar(0, 100);
    progressBar.setBounds(8, 437, 639, 24);
    progressBar.setVisible(false);
    progressBar.setStringPainted(true);
    contentPane.add(progressBar);

    JLabel lblBrowserInformation = new JLabel("Browser Information");
    lblBrowserInformation.setHorizontalAlignment(SwingConstants.LEFT);
    lblBrowserInformation.setLabelFor(textFieldBrowser);
    lblBrowserInformation.setBounds(32, 368, 174, 14);
    contentPane.add(lblBrowserInformation);

    panel = new JPanel();
    panel.setBounds(423, 325, 127, 33);
    contentPane.add(panel);
    panel.setLayout(null);

    listScrollPane = new JScrollPane();
    listScrollPane.setBounds(0, 0, 127, 33);
    panel.add(listScrollPane);

    lblDelete = new JLabel("");
    lblDelete.setBounds(552, 325, 22, 23);
    lblDelete.setVisible(false);
    lblDelete.setIcon(
            new ImageIcon(SDSupportUtility.class.getResource("/org/pentaho/support/standalone/remove.png")));
    contentPane.add(lblDelete);
    lblDelete.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            int option = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete this file ?");
            if (option == JOptionPane.YES_OPTION) {
                String sel = rowList.getSelectedValue().toString();
                String selected = dir + "/" + sel;
                File fileExists = new File(selected);
                fileExists.delete();
                model.remove(sel.indexOf(sel));
                lblDelete.setVisible(false);

            }
        }
    });

    JLabel instalType = new JLabel("Installation Type : ");
    instalType.setBounds(32, 395, 177, 23);
    instalType.setVisible(true);
    contentPane.add(instalType);

    ButtonGroup btnGrp = new ButtonGroup();

    rdbtnInstaller = new JRadioButton("Installer");
    rdbtnInstaller.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            installType = "Installer";
        }
    });
    rdbtnInstaller.setBounds(208, 395, 104, 23);
    rdbtnInstaller.setSelected(true);
    contentPane.add(rdbtnInstaller);
    btnGrp.add(rdbtnInstaller);

    rdbtnArchive = new JRadioButton("Archive");
    rdbtnArchive.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            installType = "Archive";
        }
    });
    rdbtnArchive.setBounds(333, 395, 104, 23);
    contentPane.add(rdbtnArchive);
    btnGrp.add(rdbtnArchive);

    rdbtnManual = new JRadioButton("Manual");
    rdbtnManual.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            installType = "Manual";
        }
    });
    rdbtnManual.setBounds(460, 395, 127, 27);
    contentPane.add(rdbtnManual);
    btnGrp.add(rdbtnManual);

    JLabel lblBackground = new JLabel();
    lblBackground.setIcon(new ImageIcon(
            SDSupportUtility.class.getResource("/org/pentaho/support/standalone/login-crystal-bg.jpg")));
    lblBackground.setBackground(SystemColor.controlHighlight);
    lblBackground.setHorizontalAlignment(SwingConstants.CENTER);
    lblBackground.setBounds(0, 0, 659, 488);
    contentPane.add(lblBackground);
}

From source file:com.github.lindenb.jvarkit.tools.bamviewgui.BamFileRef.java

@Override
public Collection<Throwable> call() throws Exception {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);
    List<BamFileRef> bams = new ArrayList<BamFileRef>();

    final List<String> args = getInputFiles();
    List<File> IN = new ArrayList<File>();

    if (args.isEmpty()) {
        LOG.info("NO BAM provided; Opening dialog");
        JFileChooser chooser = new JFileChooser();
        chooser.setFileFilter(new FileFilter() {
            @Override/*from  w  w w . java  2  s  .c  om*/
            public String getDescription() {
                return "Indexed BAM files.";
            }

            @Override
            public boolean accept(File f) {
                if (f.isDirectory())
                    return true;
                return acceptBam(f);
            };
        });
        chooser.setMultiSelectionEnabled(true);
        if (chooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION) {
            return wrapException("user pressed cancel");
        }
        File fs[] = chooser.getSelectedFiles();
        if (fs != null)
            IN.addAll(Arrays.asList(chooser.getSelectedFiles()));
    } else {
        for (String arg : args) {
            File filename = new File(arg);
            if (!acceptBam(filename)) {
                return wrapException(
                        "Cannot use " + filename + " as input Bam. bad extenstion ? index missing ?");
            }
            IN.add(filename);
        }
    }

    for (File in : IN) {
        try {
            bams.add(create(in));
        } catch (Exception err) {
            return wrapException(err);
        }
    }
    if (bams.isEmpty()) {
        return wrapException("No Bam file");
    }
    LOG.info("showing BAM frame");
    final BamFrame frame = new BamFrame(bams);
    frame.igvIP = super.IGV_HOST;
    frame.igvPort = super.IGV_PORT;
    try {
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
                frame.setBounds(50, 50, screen.width - 100, screen.height - 100);
                frame.setVisible(true);
            }
        });
    } catch (Exception err) {
        err.printStackTrace();
        System.exit(-1);
    }

    return RETURN_OK;
}

From source file:cs.cirg.cida.CIDAView.java

@Action
public void loadExperiment() {
    JFileChooser chooser = new JFileChooser(experimentController.getDataDirectory());
    FileNameExtensionFilter filter = new FileNameExtensionFilter(CIDAConstants.DIALOG_TXT_CSV_MSG, "txt",
            "csv");
    chooser.setFileFilter(filter);/*from  w ww. j av a  2s .  co  m*/
    chooser.setMultiSelectionEnabled(true);
    int returnVal = chooser.showOpenDialog(this.getComponent());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        try {
            File[] files = chooser.getSelectedFiles();
            String[] experimentNames = null;
            experimentNames = new String[files.length];
            for (int i = 0; i < files.length; ++i) {
                File dataFile = files[i];
                String tmpName = dataFile.getName().substring(0, dataFile.getName().lastIndexOf("."));
                if (editResultsNameCheckBox.isSelected()) {
                    CIDAInputDialog dialog = new CIDAInputDialog(this.getFrame(),
                            CIDAConstants.RENAME_EXPERIMENT_MSG, tmpName);
                    dialog.displayPrompt();
                    tmpName = dialog.getInput();
                }
                experimentNames[i] = tmpName;
            }
            experimentController.addExperiments(files, experimentNames);
            this.selectExperiment();
        } catch (CIlibIOException ex) {
            CIDAPromptDialog dialog = exceptionController.handleException(this.getFrame(), ex,
                    CIDAConstants.EXCEPTION_OCCURRED);
            dialog.displayPrompt();
        }
    }
}

From source file:ctPrincipal.Principal.java

private File openImagem(String Dir, boolean lista) {
    JFileChooser fileChooser = new JFileChooser();
    BufferedImage buff = null;//from w  w w  .  j a va 2s  .c  om
    String caminho = null;
    try {
        caminho = new File(".").getCanonicalPath() + Dir;
    } catch (IOException ex) {
        Logger.getLogger(Principal.class.getName()).log(Level.SEVERE, null, ex);
    }
    fileChooser.setCurrentDirectory(new File(caminho));
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));
    fileChooser.setAcceptAllFileFilterUsed(true);
    fileChooser.setMultiSelectionEnabled(true);
    int result = fileChooser.showOpenDialog(getComponent(0));
    if (result == JFileChooser.APPROVE_OPTION) {
        if (lista) {
            File[] selectedFile = fileChooser.getSelectedFiles();
            arquivos = new String[selectedFile.length];
            for (int i = 0; i < selectedFile.length; i++) {
                selectedFile[i].setReadable(Boolean.TRUE);
                arquivos[i] = selectedFile[i].getAbsolutePath();
            }
            jLTotal.setText("Total de Imagens : " + arquivos.length);
        } else {
            File selectedFile = fileChooser.getSelectedFile();
            return selectedFile;
        }

    }
    return null;
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.ImageFrame.java

protected File[] askUserForImageFiles() {
    ImageFilter imageFilter = new ImageFilter();
    JFileChooser fileChooser = new JFileChooser(
            WorkbenchTask.getDefaultDirPath(WorkbenchTask.IMAGES_FILE_PATH));
    fileChooser.setFileFilter(imageFilter);
    fileChooser.setDialogTitle(getResourceString("WB_CHOOSE_IMAGES"));
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileChooser.setMultiSelectionEnabled(true);

    int userAction = fileChooser.showOpenDialog(this);
    AppPreferences localPrefs = AppPreferences.getLocalPrefs();

    // remember the directory the user was last in
    localPrefs.put(WorkbenchTask.IMAGES_FILE_PATH, fileChooser.getCurrentDirectory().getAbsolutePath());

    if (userAction == JFileChooser.APPROVE_OPTION) {
        return fileChooser.getSelectedFiles();
    }/*from   w  w w. j ava2s . co  m*/

    // if for any reason we got to this point...
    return null;
}

From source file:configuration.Util.java

public static String[] simpleSearchBox(String type, boolean multi, boolean hide) {
    JFrame f = createSearchFrame();
    JFileChooser jf;
    jf = new JFileChooser(config.getExplorerPath());
    if (type.contains("d") || type.contains("D"))
        jf.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    else if (type.contains("f") || type.contains("F"))
        jf.setFileSelectionMode(JFileChooser.FILES_ONLY);
    else//ww w. ja  v a 2s  .co m
        jf.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    jf.setAcceptAllFileFilterUsed(false);
    jf.setMultiSelectionEnabled(multi);
    jf.setFileHidingEnabled(hide);
    int result = jf.showOpenDialog(f);
    f.dispose();

    if (result == JFileChooser.APPROVE_OPTION) {
        if (multi) {
            //--Save new filepath and files
            File[] files = jf.getSelectedFiles();
            String[] path = new String[files.length];
            for (int i = 0; i < files.length; i++) {
                path[i] = getCanonicalPath(files[i].getPath());
            }
            return path;
        } else {
            File file = jf.getSelectedFile();
            String[] path = new String[1];
            path[0] = getCanonicalPath(file.getPath());
            return path;
        }
    }
    String[] empty = new String[0];
    return empty;
}

From source file:org.jets3t.apps.uploader.Uploader.java

/**
 * Handles GUI actions.//from ww w  .j  ava  2s .  com
 */
public void actionPerformed(ActionEvent actionEvent) {
    if ("Next".equals(actionEvent.getActionCommand())) {
        wizardStepForward();
    } else if ("Back".equals(actionEvent.getActionCommand())) {
        wizardStepBackward();
    } else if ("ChooseFile".equals(actionEvent.getActionCommand())) {
        JFileChooser fileChooser = new JFileChooser();

        if (validFileExtensions.size() > 0) {
            UploaderFileExtensionFilter filter = new UploaderFileExtensionFilter("Allowed files",
                    validFileExtensions);
            fileChooser.setFileFilter(filter);
        }

        fileChooser.setMultiSelectionEnabled(fileMaxCount > 1);
        fileChooser.setDialogTitle("Choose file" + (fileMaxCount > 1 ? "s" : "") + " to upload");
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setApproveButtonText("Choose file" + (fileMaxCount > 1 ? "s" : ""));

        int returnVal = fileChooser.showOpenDialog(ownerFrame);
        if (returnVal != JFileChooser.APPROVE_OPTION) {
            return;
        }

        List fileList = new ArrayList();
        if (fileChooser.getSelectedFiles().length > 0) {
            fileList.addAll(Arrays.asList(fileChooser.getSelectedFiles()));
        } else {
            fileList.add(fileChooser.getSelectedFile());
        }
        if (checkProposedUploadFiles(fileList)) {
            wizardStepForward();
        }
    } else if ("CancelUpload".equals(actionEvent.getActionCommand())) {
        if (uploadCancelEventTrigger != null) {
            uploadCancelEventTrigger.cancelTask(this);
            progressBar.setValue(0);
        } else {
            log.warn("Ignoring attempt to cancel file upload when cancel trigger is not available");
        }
    } else {
        log.warn("Unrecognised action command, ignoring: " + actionEvent.getActionCommand());
    }
}

From source file:org.jets3t.apps.cockpit.Cockpit.java

/**
 * Event handler for this application, handles all menu items.
 *///  w  w w  . j a v  a2 s  .  c  om
public void actionPerformed(ActionEvent event) {
    // Service Menu Events
    if ("LoginEvent".equals(event.getActionCommand())) {
        loginEvent(null);
    } else if ("LogoutEvent".equals(event.getActionCommand())) {
        logoutEvent();
    } else if (event.getActionCommand() != null && event.getActionCommand().startsWith("LoginSwitch")) {
        String loginName = event.getActionCommand().substring("LoginSwitch:".length());
        ProviderCredentials credentials = loginAwsCredentialsMap.get(loginName);
        loginEvent(credentials);
    } else if ("QuitEvent".equals(event.getActionCommand())) {
        System.exit(0);
    }

    // Bucket Events.
    else if ("ViewBucketProperties".equals(event.getActionCommand())) {
        listBucketProperties();
    } else if ("RefreshBuckets".equals(event.getActionCommand())) {
        listAllBuckets();
    } else if ("CreateBucket".equals(event.getActionCommand())) {
        createBucketAction();
    } else if ("DeleteBucket".equals(event.getActionCommand())) {
        deleteSelectedBucket();
    } else if ("ManageDistributions".equals(event.getActionCommand())) {
        S3Bucket[] buckets = bucketTableModel.getBuckets();
        String[] bucketNames = new String[buckets.length];
        for (int i = 0; i < buckets.length; i++) {
            bucketNames[i] = buckets[i].getName();
        }
        ManageDistributionsDialog.showDialog(ownerFrame, cloudFrontService, bucketNames, this);
    } else if ("AddThirdPartyBucket".equals(event.getActionCommand())) {
        addThirdPartyBucket();
    } else if ("UpdateBucketACL".equals(event.getActionCommand())) {
        updateBucketAccessControlList();
    } else if ("UpdateBucketRequesterPaysStatus".equals(event.getActionCommand())) {
        updateBucketRequesterPaysSetting();
    }

    // Object Events
    else if ("ViewOrModifyObjectAttributes".equals(event.getActionCommand())) {
        displayObjectsAttributesDialog();
    } else if ("CopyObjects".equals(event.getActionCommand())) {
        copyObjects();
    } else if ("RefreshObjects".equals(event.getActionCommand())) {
        listObjects();
    } else if ("UpdateObjectACL".equals(event.getActionCommand())) {
        displayAclModificationDialog();
    } else if ("GeneratePublicGetURLs".equals(event.getActionCommand())) {
        generatePublicGetUrls();
    } else if ("GenerateTorrentURL".equals(event.getActionCommand())) {
        generateTorrentUrl();
    } else if ("DeleteObjects".equals(event.getActionCommand())) {
        deleteSelectedObjects();
    } else if ("DownloadObjects".equals(event.getActionCommand())) {
        downloadSelectedObjects();
    } else if ("UploadFiles".equals(event.getActionCommand())) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setMultiSelectionEnabled(true);
        fileChooser.setDialogTitle("Choose files to upload");
        fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        fileChooser.setApproveButtonText("Upload files");
        fileChooser.setCurrentDirectory(fileChoosersLastUploadDirectory);

        int returnVal = fileChooser.showOpenDialog(ownerFrame);
        if (returnVal != JFileChooser.APPROVE_OPTION) {
            return;
        }

        final File[] uploadFiles = fileChooser.getSelectedFiles();
        if (uploadFiles.length == 0) {
            return;
        }

        // Save the chosen directory location for next time.
        fileChoosersLastUploadDirectory = uploadFiles[0].getParentFile();

        uploadFiles(uploadFiles);
    } else if (event.getSource().equals(filterObjectsCheckBox)) {
        if (filterObjectsCheckBox.isSelected()) {
            filterObjectsPanel.setVisible(true);
        } else {
            filterObjectsPanel.setVisible(false);
            filterObjectsPrefix.setText("");
            if (filterObjectsDelimiter.getSelectedIndex() != 0) {
                filterObjectsDelimiter.setSelectedIndex(0);
            }
        }
    }

    // Tools events
    else if ("BucketLogging".equals(event.getActionCommand())) {
        S3Bucket[] buckets = bucketTableModel.getBuckets();
        BucketLoggingDialog.showDialog(ownerFrame, s3ServiceMulti.getS3Service(), buckets, this);
    }

    // Preference Events
    else if ("PreferencesDialog".equals(event.getActionCommand())) {
        PreferencesDialog.showDialog(cockpitPreferences, ownerFrame, this);

        // Save a user's preferences if requested, otherwise wipe any existing preferences file.
        File cockpitPreferencesPropertiesFile = new File(cockpitHomeDirectory,
                Constants.COCKPIT_PROPERTIES_FILENAME);
        if (cockpitPreferences.isRememberPreferences()) {
            try {
                Properties properties = cockpitPreferences.toProperties();
                if (!cockpitHomeDirectory.exists()) {
                    cockpitHomeDirectory.mkdir();
                }
                properties.list(new PrintStream(new FileOutputStream(cockpitPreferencesPropertiesFile)));
            } catch (IOException e) {
                String message = "Unable to save your preferences";
                log.error(message, e);
                ErrorDialog.showDialog(ownerFrame, this, message, e);
            }
        } else if (cockpitPreferencesPropertiesFile.exists()) {
            // User elected not to store preferences, delete the existing preferences file.
            cockpitPreferencesPropertiesFile.delete();
        }

        if (cockpitPreferences.isEncryptionPasswordSet()) {
            try {
                encryptionUtil = new EncryptionUtil(cockpitPreferences.getEncryptionPassword(),
                        cockpitPreferences.getEncryptionAlgorithm(), EncryptionUtil.DEFAULT_VERSION);
            } catch (Exception e) {
                String message = "Unable to start encryption utility";
                log.error(message, e);
                ErrorDialog.showDialog(ownerFrame, this, message, e);
            }
        } else {
            encryptionUtil = null;
        }
    }

    // Ooops...
    else {
        log.debug("Unrecognised ActionEvent command '" + event.getActionCommand() + "' in " + event);
    }
}

From source file:edu.ku.brc.specify.tasks.WorkbenchTask.java

/**
 * Imports a set of image files, creating a new row per file, to the provided {@link Workbench} parameter.  If the
 * given {@link Workbench} is <code>null</code>, a new {@link Workbench} is created.
 * //from   w ww .ja va2  s .  co  m
 * @param workbenchArg the {@link Workbench} to append rows to, or <code>null</code> if a new {@link Workbench} should be created
 * @param doOneImagePerRow indicates whether the images are assign to a single row or not.
 */
public void importCardImages(Workbench workbench, final boolean doOneImagePerRow) {
    // ask the user to select the files to import
    final ImageFilter imageFilter = new ImageFilter();
    JFileChooser chooser = new JFileChooser(getDefaultDirPath(IMAGES_FILE_PATH));
    chooser.setDialogTitle(getResourceString("WB_CHOOSE_IMAGES"));
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setMultiSelectionEnabled(true);
    chooser.setFileFilter(imageFilter);

    if (chooser.showOpenDialog(UIRegistry.get(UIRegistry.FRAME)) != JFileChooser.APPROVE_OPTION) {
        UIRegistry.getStatusBar().setText("");
        return;
    }

    AppPreferences localPrefs = AppPreferences.getLocalPrefs();
    localPrefs.put(IMAGES_FILE_PATH, chooser.getCurrentDirectory().getAbsolutePath());

    // Start by looping through the files and checking for image file extensions
    // weed out the bad files.
    final Vector<File> fileList = new Vector<File>();
    if (!filterSelectedFileNames(chooser.getSelectedFiles(), fileList, imageFilter)) {
        return;
    }

    for (File f : fileList) {
        if (!ImageFrame.testImageFile(f.getAbsolutePath())) {
            JOptionPane.showMessageDialog(UIRegistry.getMostRecentWindow(),
                    String.format(getResourceString("WB_WRONG_IMAGE_TYPE_OR_CORRUPTED_IMAGE"),
                            new Object[] { f.getAbsolutePath() }),
                    UIRegistry.getResourceString("WARNING"), JOptionPane.ERROR_MESSAGE);
            return;
        }
    }

    boolean creatingNewWb = workbench == null;

    if (creatingNewWb) // create a new Workbench
    {
        List<?> selection = selectExistingTemplate(null, "WorkbenchImportImages");
        //Pair<Boolean, WorkbenchTemplate> selection = selectExistingTemplate(null, "WorkbenchImportImages");

        if (selection.size() == 0 || !(Boolean) selection.get(0)) {
            return; //cancelled
        }

        WorkbenchTemplate workbenchTemplate = selection.size() > 1 ? (WorkbenchTemplate) selection.get(1)
                : null;

        if (workbenchTemplate == null) {
            // create a new WorkbenchTemplate
            TemplateEditor dlg = null;
            try {
                dlg = showColumnMapperDlg(null, null, "WB_MAPPING_EDITOR");
            } catch (Exception ex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(WorkbenchTask.class, ex);
                log.error(ex);
            }
            if (dlg != null && !dlg.isCancelled()) {
                workbenchTemplate = createTemplate(dlg, null);
            }
            if (dlg != null) {
                dlg.dispose();
            }

        } else {
            workbenchTemplate = cloneWorkbenchTemplate(workbenchTemplate);
        }
        if (workbenchTemplate != null) {
            workbench = createNewWorkbenchDataObj("", workbenchTemplate);
        }

    }

    if (workbench != null) // this should always hold, but whatev
    {
        UIRegistry.writeGlassPaneMsg(String.format(getResourceString("WB_LOADING_IMGS_DATASET"),
                new Object[] { workbench.getName() }), GLASSPANE_FONT_SIZE);
        doImageImport(workbench, fileList, creatingNewWb, doOneImagePerRow);
    }
}

From source file:app.RunApp.java

/**
 * Load multiple datasets/*  ww  w .ja  va2  s  . c o m*/
 * 
 * @param returnVal Value returned from openDialog
 * @param chooser Chooser
 * @return Positive number if successfull and negative otherwise
 */
private int loadMultiDataset(int returnVal, JFileChooser chooser) {

    if (returnVal == JFileChooser.OPEN_DIALOG) {
        File[] files = chooser.getSelectedFiles();

        for (File f1 : files) {
            String datasetName = f1.getName();
            datasetName = datasetName.substring(0, datasetName.length() - 5);

            if (datasetNames.contains(datasetName)) {
                JOptionPane.showMessageDialog(null, "The dataset is duplicated.", "alert",
                        JOptionPane.ERROR_MESSAGE);
                return -1;
            }

            String arffFilename = f1.getAbsolutePath();
            xmlFilename = DataIOUtils.getXMLString(arffFilename);
            xmlFilename = DataIOUtils.getFilePath(xmlFilename);

            boolean isMeka = false;

            String xmlPath = arffFilename.substring(0, arffFilename.length() - 5) + ".xml";

            FileReader fr;
            try {
                fr = new FileReader(arffFilename);
                BufferedReader bf = new BufferedReader(fr);

                String sString = bf.readLine();
                int labelFound = 0;
                String labelName;
                String[] labelNamesFound;

                isMeka = DataIOUtils.isMeka(sString);
                areMeka.add(isMeka);

                if (isMeka) {
                    isMeka = true;

                    int labelCount = DataIOUtils.getLabelsFromARFF(sString);

                    if (labelCount > 0) {
                        labelNamesFound = new String[labelCount];

                        while (labelFound < labelCount) {
                            sString = bf.readLine();
                            labelName = DataIOUtils.getLabelNameFromLine(sString);

                            if (labelName != null) {
                                labelNamesFound[labelFound] = labelName;
                                labelFound++;
                            }
                        }
                    } else {
                        labelCount = Math.abs(labelCount);
                        labelNamesFound = new String[labelCount];

                        String[] sStrings = new String[labelCount];

                        while (!(sString = bf.readLine()).contains("@data")) {
                            if (!sString.trim().equals("")) {
                                for (int s = 0; s < labelCount - 1; s++) {
                                    sStrings[s] = sStrings[s + 1];
                                }
                                sStrings[labelCount - 1] = sString;
                            }
                        }

                        for (int i = 0; i < labelCount; i++) {
                            labelName = DataIOUtils.getLabelNameFromLine(sStrings[i]);

                            if (labelName != null) {
                                labelNamesFound[labelFound] = labelName;
                                labelFound++;
                            }
                        }
                    }

                    BufferedWriter bwXml = new BufferedWriter(new FileWriter(xmlPath));
                    PrintWriter wrXml = new PrintWriter(bwXml);

                    DataIOUtils.writeXMLFile(wrXml, labelNamesFound);

                    bwXml.close();
                    wrXml.close();

                    xmlFilename = DataIOUtils.getFilePath(xmlPath);
                } else {
                    isMeka = false;
                }
            } catch (FileNotFoundException ex) {
                Logger.getLogger(RunApp.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(RunApp.class.getName()).log(Level.SEVERE, null, ex);
            }

            try {
                MultiLabelInstances current = new MultiLabelInstances(arffFilename, xmlFilename);

                if (isMeka) {
                    File f2 = new File(xmlFilename);
                    f2.delete();
                }

                listDatasets.add(current);
                datasetNames.add(datasetName);
                list.addElement(datasetName);
            } catch (InvalidDataFormatException ex) {
                Logger.getLogger(RunApp.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    return 1;
}