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:de.evaluationtool.gui.EvaluationFrameActionListener.java

private void saveReference(boolean mustSupportEvaluation, boolean includeEvaluation)
        throws FileNotFoundException {
    Set<ReferenceFormat> formats = mustSupportEvaluation
            ? ReferenceFormats.REFERENCE_FORMATS.evaluationIncludingFormats
            : ReferenceFormats.REFERENCE_FORMATS.formats;
    formats.retainAll(ReferenceFormats.REFERENCE_FORMATS.writeableFormats);

    ReferenceFormat format = formatChooser(formats);
    if (format == null) {
        return;//from w w  w .  j  a  v  a 2s .co  m
    }

    JFileChooser chooser = new JFileChooser("Save reference. Please choose a file.");
    chooser.setCurrentDirectory(frame.defaultDirectory);
    chooser.setFileSelectionMode(
            format.readsDirectory() ? JFileChooser.DIRECTORIES_ONLY : JFileChooser.FILES_ONLY);
    if (format.getFileExtension() != null) {
        chooser.addChoosableFileFilter(
                new FilesystemFilter(format.getFileExtension(), format.getDescription()));
    } else {
        chooser.setAcceptAllFileFilterUsed(true);
    }

    int returnVal = chooser.showSaveDialog(frame);
    if (returnVal != JFileChooser.APPROVE_OPTION)
        return;
    System.out.print("Saving...");
    format.writeReference(frame.reference, chooser.getSelectedFile(), includeEvaluation);
    //frame.loadPositiveNegativeNT(chooser.getSelectedFile());
    System.out.println("saving finished.");
}

From source file:coreferenceresolver.gui.MarkupGUI.java

public MarkupGUI() throws IOException {
    highlightPainters = new ArrayList<>();

    for (int i = 0; i < COLORS.length; ++i) {
        DefaultHighlighter.DefaultHighlightPainter highlightPainter = new DefaultHighlighter.DefaultHighlightPainter(
                COLORS[i]);// www  .j  a va  2  s . co  m
        highlightPainters.add(highlightPainter);
    }

    defaulPath = FileUtils.readFileToString(new File(".\\src\\coreferenceresolver\\gui\\defaultpath"));
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLayout(new BorderLayout());
    this.setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());

    JMenuBar menuBar = new JMenuBar();
    JMenu fileMenu = new JMenu("File");
    //create menu items
    JMenuItem importMenuItem = new JMenuItem("Import");

    JMenuItem exportMenuItem = new JMenuItem("Export");

    fileMenu.add(importMenuItem);
    fileMenu.add(exportMenuItem);

    menuBar.add(fileMenu);

    this.setJMenuBar(menuBar);

    ScrollablePanel mainPanel = new ScrollablePanel();
    mainPanel.setScrollableWidth(ScrollablePanel.ScrollableSizeHint.NONE);
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

    //IMPORT BUTTON
    importMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //                MarkupGUI.reviewElements.clear();
            //                MarkupGUI.markupReviews.clear();                
            JFileChooser markupFileChooser = new JFileChooser(defaulPath);
            markupFileChooser.setDialogTitle("Choose your markup file");
            markupFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

            if (markupFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                final JDialog d = new JDialog();
                JPanel p1 = new JPanel(new GridBagLayout());
                p1.add(new JLabel("Please Wait..."), new GridBagConstraints());
                d.getContentPane().add(p1);
                d.setSize(100, 100);
                d.setLocationRelativeTo(null);
                d.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                d.setModal(true);

                SwingWorker<?, ?> worker = new SwingWorker<Void, Void>() {
                    protected Void doInBackground() throws IOException, BadLocationException {
                        readMarkupFile(markupFileChooser.getSelectedFile().getAbsolutePath());
                        for (int i = 0; i < markupReviews.size(); ++i) {
                            mainPanel.add(newReviewPanel(markupReviews.get(i), i));
                        }
                        return null;
                    }

                    protected void done() {
                        MarkupGUI.this.revalidate();
                        d.dispose();
                    }
                };
                worker.execute();
                d.setVisible(true);
            } else {
                return;
            }
        }
    });

    //EXPORT BUTTON: GET NEW VALUE (REF, TYPE) OF NPs      
    exportMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JFileChooser markupFileChooser = new JFileChooser(defaulPath);
            markupFileChooser.setDialogTitle("Choose where your markup file saved");
            markupFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

            if (markupFileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                final JDialog d = new JDialog();
                JPanel p1 = new JPanel(new GridBagLayout());
                p1.add(new JLabel("Please Wait..."), new GridBagConstraints());
                d.getContentPane().add(p1);
                d.setSize(100, 100);
                d.setLocationRelativeTo(null);
                d.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
                d.setModal(true);

                SwingWorker<?, ?> worker = new SwingWorker<Void, Void>() {
                    protected Void doInBackground() throws IOException {
                        for (Review review : markupReviews) {
                            generateNPsRef(review);
                        }
                        int i = 0;
                        for (ReviewElement reviewElement : reviewElements) {
                            int j = 0;
                            for (Element element : reviewElement.elements) {
                                String newType = element.typeSpinner.getValue().toString();
                                if (newType.equals("Object")) {
                                    markupReviews.get(i).getNounPhrases().get(j).setType(0);
                                } else if (newType.equals("Attribute")) {
                                    markupReviews.get(i).getNounPhrases().get(j).setType(3);
                                } else if (newType.equals("Other")) {
                                    markupReviews.get(i).getNounPhrases().get(j).setType(1);
                                } else if (newType.equals("Candidate")) {
                                    markupReviews.get(i).getNounPhrases().get(j).setType(2);
                                }
                                ++j;
                            }
                            ++i;
                        }
                        initMarkupFile(markupFileChooser.getSelectedFile().getAbsolutePath() + File.separator
                                + "markup.out.txt");
                        return null;
                    }

                    protected void done() {
                        d.dispose();
                        try {
                            Desktop.getDesktop()
                                    .open(new File(markupFileChooser.getSelectedFile().getAbsolutePath()));
                        } catch (IOException ex) {
                            Logger.getLogger(MarkupGUI.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                };
                worker.execute();
                d.setVisible(true);
            } else {
                return;
            }
        }
    });

    JScrollPane scrollMainPane = new JScrollPane(mainPanel);
    scrollMainPane.getVerticalScrollBar().setUnitIncrement(16);
    scrollMainPane.setPreferredSize(new Dimension(this.getWidth(), this.getHeight()));
    scrollMainPane.setSize(this.getWidth(), this.getHeight());
    this.setResizable(false);
    this.add(scrollMainPane, BorderLayout.CENTER);
    this.setExtendedState(JFrame.MAXIMIZED_BOTH);
    this.pack();
}

From source file:com.akman.excel.view.frmExportExcel.java

private void btnSelectImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectImageActionPerformed
    JFileChooser chooser = new JFileChooser();

    FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "jpg", "png", "gif", "bmp");
    chooser.setFileFilter(filter);/*from   w w w.ja  v a 2  s . c om*/

    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setDialogTitle("Select The Image");
    chooser.setMultiSelectionEnabled(false);
    int res = chooser.showOpenDialog(null);
    if (res == JFileChooser.APPROVE_OPTION) {

        //Saving file inside the file
        File file = chooser.getSelectedFile();

        //        if(!file.equals(filter))
        //        {
        //        JOptionPane.showMessageDialog(null, "Wrong File Selected","ERROR",JOptionPane.ERROR_MESSAGE);
        //        return;
        //        }
        //System.out.println(file.getAbsolutePath());
        ImageIcon image = new ImageIcon(file.getAbsolutePath());

        fileNameSignature = file.getAbsolutePath();

        // Get Width And Height of PicLabel
        Rectangle rect = lblImage.getBounds();

        //System.out.println(lblImage.getBounds());
        //Scaling the image to fit in the picLabel
        Image scaledimage = image.getImage().getScaledInstance(rect.width, rect.height, Image.SCALE_DEFAULT);
        //converting the image back to image icon to make an acceptable picLabel
        image = new ImageIcon(scaledimage);

        lblImage.setIcon(image);

        txtPathSig.setText(fileNameSignature);

        try {

            File images = new File(fileNameSignature);

            FileInputStream fis = new FileInputStream(images);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            byte[] buf = new byte[1024];

            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);
            }

            person_image = bos.toByteArray();

        } catch (Exception e) {

            JOptionPane.showMessageDialog(null, e);
        }

    }
}

From source file:AST.DesignPatternDetection.java

private void btProgramPathActionPerformed(ActionEvent e) {
    // TODO add your code here
    JFileChooser f2 = new JFileChooser();
    f2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    f2.showDialog(null, null);/*from  ww w .j  a  v a2 s .c om*/
    tfProgramPath.setText(f2.getSelectedFile().toString());
    //System.out.println(f.getCurrentDirectory());
    //System.out.println(f.getSelectedFile());
}

From source file:AST.DesignPatternDetection.java

private void btPathFinderActionPerformed(ActionEvent e) {
    // TODO add your code here
    JFileChooser f = new JFileChooser();
    f.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    f.showDialog(null, null);/* w  w w . j av a  2  s. com*/
    tfPath.setText(f.getSelectedFile().toString());

    vertices.clear();
    dugumler.clear();
    methods.clear();

    //System.out.println(f.getCurrentDirectory());
    //System.out.println(f.getSelectedFile());
}

From source file:com.akman.excel.view.frmExportExcel.java

private void btnAddFileActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_btnAddFileActionPerformed
{//GEN-HEADEREND:event_btnAddFileActionPerformed

    JFileChooser chooser = new JFileChooser();

    FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel files", "xlsx", "xlsm", "xlt", "xlsb",
            "xltx", "xltm", "xls", "xlt", "xls");

    chooser.setFileFilter(filter);/*from  ww w . j a va  2s .c o  m*/
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    chooser.setDialogTitle("Select The Image");
    chooser.setMultiSelectionEnabled(false);

    int res = chooser.showOpenDialog(null);

    if (res == JFileChooser.APPROVE_OPTION) {

        File file = chooser.getSelectedFile();

        // checking file extension. it must be excel file. 
        if (file.equals(filter)) {
            JOptionPane.showMessageDialog(null, "Wrong File selected", "ERROR", JOptionPane.ERROR_MESSAGE);
            return;
        }

        fileName = file.getAbsolutePath();
        txtPath.setText(fileName);

    }

}

From source file:com.evanbelcher.DrillBook.display.DBMenuBar.java

/**
 * Saves the current file under a new name/path
 *
 * @throws InterruptedException if there is an error when waiting for the saves to finish
 *//*  w  w  w  .  j av  a2s . c om*/
private void saveAs() throws InterruptedException {
    if (askToSave()) {

        final JFileChooser fc = new JFileChooser(Main.getFilePath());
        fc.setFileFilter(new DrillFileFilter());
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int returnVal = fc.showSaveDialog(this);
        File file = fc.getSelectedFile();

        String name, path;

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                path = file.getCanonicalPath();
                path = path.substring(0, Math.max(path.lastIndexOf('\\'), path.lastIndexOf('/')) + 1);
                name = file.getName().toLowerCase().endsWith(".drill") ? file.getName()
                        : file.getName() + ".drill";
                Main.setFilePath(path);
                Main.setPagesFileName(name);
                Main.savePages().join();
                Main.saveState().join();
                Main.load(false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:edu.harvard.mcz.imagecapture.jobs.JobRepeatOCR.java

private List<File> getFileList() {
    String pathToCheck = "";
    if (scan != SCAN_ALL) {
        // Find the path in which to include files.
        File imagebase = null; // place to start the scan from, imagebase directory for SCAN_ALL
        File startPoint = null;/*from   w  w  w .  j  a  va  2  s .  c o m*/
        // If it isn't null, retrieve the image base directory from properties, and test for read access.
        if (Singleton.getSingletonInstance().getProperties().getProperties()
                .getProperty(ImageCaptureProperties.KEY_IMAGEBASE) == null) {
            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                    "Can't start scan.  Don't know where images are stored.  Set imagbase property.",
                    "Can't Scan.", JOptionPane.ERROR_MESSAGE);
        } else {
            imagebase = new File(Singleton.getSingletonInstance().getProperties().getProperties()
                    .getProperty(ImageCaptureProperties.KEY_IMAGEBASE));
            if (imagebase != null) {
                if (imagebase.canRead()) {
                    startPoint = imagebase;
                } else {
                    // If it can't be read, null out imagebase
                    imagebase = null;
                }
            }
            if (scan == SCAN_SPECIFIC && startPointSpecific != null && startPointSpecific.canRead()) {
                // A scan start point has been provided, don't launch a dialog.
                startPoint = startPointSpecific;
            }
            if (imagebase == null || scan == SCAN_SELECT) {
                // launch a file chooser dialog to select the directory to scan
                final JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                if (scan == SCAN_SELECT && startPointSpecific != null && startPointSpecific.canRead()) {
                    fileChooser.setCurrentDirectory(startPointSpecific);
                } else {
                    if (Singleton.getSingletonInstance().getProperties().getProperties()
                            .getProperty(ImageCaptureProperties.KEY_LASTPATH) != null) {
                        fileChooser
                                .setCurrentDirectory(new File(Singleton.getSingletonInstance().getProperties()
                                        .getProperties().getProperty(ImageCaptureProperties.KEY_LASTPATH)));
                    }
                }
                int returnValue = fileChooser.showOpenDialog(Singleton.getSingletonInstance().getMainFrame());
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                    log.debug("Selected base directory: " + file.getName() + ".");
                    startPoint = file;
                } else {
                    //TODO: handle error condition
                    log.error("Directory selection cancelled by user.");
                }
                //TODO: Filechooser to pick path, then save (if SCAN_ALL) imagebase property. 
                //Perhaps.  Might be undesirable behavior.
                //Probably better to warn that imagebase is null;
            }

            // Check that startPoint is or is within imagebase.
            if (!ImageCaptureProperties.isInPathBelowBase(startPoint)) {
                String base = Singleton.getSingletonInstance().getProperties().getProperties()
                        .getProperty(ImageCaptureProperties.KEY_IMAGEBASE);
                log.error("Tried to scan directory (" + startPoint.getPath()
                        + ") outside of base image directory (" + base + ")");
                String message = "Can't scan and database files outside of base image directory (" + base + ")";
                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(), message,
                        "Can't Scan outside image base directory.", JOptionPane.YES_NO_OPTION);
            } else {

                // run in separate thread and allow cancellation and status reporting

                // walk through directory tree

                if (!startPoint.canRead()) {
                    JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                            "Can't start scan.  Unable to read selected directory: " + startPoint.getPath(),
                            "Can't Scan.", JOptionPane.YES_NO_OPTION);
                } else {
                    pathToCheck = ImageCaptureProperties.getPathBelowBase(startPoint);
                }
            }
        }
    }

    // Retrieve a list of all specimens in state OCR
    SpecimenLifeCycle sls = new SpecimenLifeCycle();
    Specimen pattern = new Specimen();
    pattern.setWorkFlowStatus(WorkFlowStatus.STAGE_0);
    List<Specimen> specimens = sls.findByExample(pattern);
    ArrayList<File> files = new ArrayList<File>();
    for (int i = 0; i < specimens.size(); i++) {
        Specimen s = specimens.get(i);
        Set<ICImage> images = s.getICImages();
        Iterator<ICImage> iter = images.iterator();
        while (iter.hasNext() && runStatus != RunStatus.STATUS_TERMINATED) {
            ICImage image = (ICImage) iter.next();
            if (scan == SCAN_ALL || image.getPath().startsWith(pathToCheck)) {
                // Add image for specimen to list to check
                File imageFile = new File(
                        ImageCaptureProperties.assemblePathWithBase(image.getPath(), image.getFilename()));
                files.add(imageFile);
                counter.incrementFilesSeen();
            }
        }
    }
    String message = "Found " + files.size() + " Specimen records on which to repeat OCR.";
    log.debug(message);
    Singleton.getSingletonInstance().getMainFrame().setStatusMessage(message);

    return files;
}

From source file:com.evanbelcher.DrillBook.display.DBMenuBar.java

/**
 * Gets the show to open and opens the respective json file.
 *//*  www.  ja  v  a 2  s.  c om*/
private void openShow() {
    if (askToSave()) {

        File file;
        final JFileChooser fc = new JFileChooser(Main.getFilePath());
        fc.setFileFilter(new DrillFileFilter());
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int returnVal;
        do {
            returnVal = fc.showOpenDialog(this);
            file = fc.getSelectedFile();
        } while (returnVal != JFileChooser.CANCEL_OPTION && returnVal != JFileChooser.ERROR_OPTION
                && !file.exists());
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                String name, path;
                path = file.getCanonicalPath();
                path = path.substring(0, Math.max(path.lastIndexOf('\\'), path.lastIndexOf('/')) + 1);
                name = file.getName().toLowerCase().endsWith(".drill") ? file.getName()
                        : file.getName() + ".drill";
                Main.setFilePath(path);
                Main.setPagesFileName(name);
                Main.load(false);
                desktop.createNewInternalFrames();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:net.sf.jclal.gui.view.components.chart.ExternalBasicChart.java

/**
 *
 * @return Create the menu that allows load the result from others
 * experiments.//from w ww  .  j  a va  2 s  . c  om
 */
private JMenu createMenu() {

    final JMenu fileMenu = new JMenu("Options");

    final JFileChooser f = new JFileChooser();
    f.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    fileMenu.add("Add report file or directory").addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (curveOptions != null) {
                curveOptions.setVisible(false);
                curveOptions = null;
            }
            int action = f.showOpenDialog(fileMenu);

            if (action == JFileChooser.APPROVE_OPTION) {

                loadReportFile(f.getSelectedFile());

            }

        }
    });

    fileMenu.add("Area under learning curve (ALC)").addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {

            if (comboBox.getItemCount() != 0) {

                if (!comboBox.getSelectedItem().toString().isEmpty()) {

                    StringBuilder st = new StringBuilder();

                    st.append("Measure: ").append(comboBox.getSelectedItem()).append("\n\n");

                    for (int query = 0; query < queryNames.size(); query++) {

                        double value = LearningCurveUtility.getArea(evaluationsCollection.get(query),
                                comboBox.getSelectedItem().toString());

                        String valueString = String.format("%.3f", value);

                        st.append(queryNames.get(query)).append(": ").append(valueString).append("\n");

                    }

                    JOptionPane.showMessageDialog(content, st.toString(), "Area under the learning curve",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            }
        }
    });

    fileMenu.add("Clear").addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {

            queryNames = new ArrayList<String>();
            evaluationsCollection = new ArrayList<List<AbstractEvaluation>>();
            comboBox.removeAllItems();
            controlCurveColor = new HashMap<String, Color>();
            colors.clear();
            data = null;
            set.clear();
            curveOptions.setVisible(false);
            curveOptions = null;
            setSeries.clear();
            passiveEvaluation = null;

        }
    });

    fileMenu.add("Curve options").addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {

            data = informationTable();

            if (queryNames.isEmpty()) {
                JOptionPane.showMessageDialog(null, "Please add curves");
                return;
            }
            if (curveOptions == null) {
                curveOptions = new LearningCurvesVisualTable(ExternalBasicChart.this);
            } else {
                curveOptions.setVisible(true);
            }

        }

    });

    final JCheckBox viewPoints = new JCheckBox("View points's shapes");
    viewPoints.setSelected(false);

    viewPoints.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            viewPointsForm = viewPoints.isSelected();
            jComboBoxItemStateChanged();
        }
    });

    fileMenu.add(viewPoints);

    final JCheckBox withOutColor = new JCheckBox("View without color");
    withOutColor.setSelected(false);

    withOutColor.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            viewWithOutColor = withOutColor.isSelected();
            jComboBoxItemStateChanged();
        }
    });

    fileMenu.add(withOutColor);

    return fileMenu;
}