Example usage for javax.swing JFileChooser addChoosableFileFilter

List of usage examples for javax.swing JFileChooser addChoosableFileFilter

Introduction

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

Prototype

@BeanProperty(preferred = true, description = "Adds a filter to the list of user choosable file filters.")
public void addChoosableFileFilter(FileFilter filter) 

Source Link

Document

Adds a filter to the list of user choosable file filters.

Usage

From source file:psidev.psi.mi.validator.client.gui.DragAndDropValidator.java

/**
 * Sets up the menu bar of the main window.
 *
 * @param frame the frame onto which we attach the menu bar
 * @param table the table that allow to command the validator.
 * @param level the level of log message.
 *//*from  w w w  .ja v  a 2  s  . c o m*/
public static void setupMenus(final JFrame frame, final Validator validator, final ValidatorTable table,
        final MessageLevel level) {

    // Create the fileMenu bar
    JMenuBar menuBar = new JMenuBar();

    final UserPreferences preferences = validator.getUserPreferences();

    ////////////////////////////
    // 1. Create a file menu
    JMenu fileMenu = new JMenu("File");
    menuBar.add(fileMenu);

    // Create a file Menu items
    JMenuItem openFile = new JMenuItem("Open file...");
    openFile.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            GuiUserPreferences guiPrefs = new GuiUserPreferences(preferences);

            File lastDirectory = userPreferences.getLastOpenedDirectory();

            JFileChooser fileChooser = new JFileChooser(lastDirectory);
            fileChooser.addChoosableFileFilter(new XmlFileFilter());

            // Open file dialog.
            fileChooser.showOpenDialog(frame);

            File selected = fileChooser.getSelectedFile();

            if (selected != null) {
                userPreferences.setLastOpenedDirectory(selected.getParentFile());

                // start validation of the selected file.
                ValidatorTableRow row = new ValidatorTableRow(selected, level, true);

                table.addTableRow(row);
            }
        }
    });
    fileMenu.add(openFile);

    // exit menu item
    JMenuItem exit = new JMenuItem("Exit");
    exit.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            System.exit(0);
        }
    });
    fileMenu.add(exit);

    ///////////////////////////////
    // 2. TODO setup messages menu

    //        JMenu msgMenu = new JMenu( "Messages" );
    //        menuBar.add( msgMenu );
    //
    //        // Create a clear all messages item
    //        JMenuItem clearAll = new JMenuItem( "Clear all" );
    //        openFile.addActionListener( new ActionListener() {
    //
    //            public void actionPerformed( ActionEvent e ) {
    //
    //                // remove all elements
    //                table.removeAllRows( );
    //            }
    //        } );
    //        msgMenu.add( clearAll );

    //////////////////////////////
    // Log level

    // TODO create a menu that allows to switch log level at run time.

    /////////////////////////
    // 3. setup help menu
    JMenu helpMenu = new JMenu("Help");
    menuBar.add(helpMenu);

    JMenuItem about = new JMenuItem("About...");
    about.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            JOptionPane msg = new JOptionPane("Version " + VERSION + NEW_LINE + "Authors: " + AUTHORS);
            JDialog dialog = msg.createDialog(frame, "About PSI Validator");
            dialog.setResizable(true);
            dialog.pack();
            dialog.setVisible(true);
        }
    });
    helpMenu.add(about);

    // Install the fileMenu bar in the frame
    frame.setJMenuBar(menuBar);
}

From source file:ro.nextreports.designer.action.report.ViewReportSqlAction.java

public void actionPerformed(ActionEvent e) {

    JFileChooser fc = new JFileChooser();
    fc.setDialogTitle(I18NSupport.getString("select.next.reports.file"));
    fc.setAcceptAllFileFilterUsed(false);
    fc.addChoosableFileFilter(new NextFileFilter());
    int returnVal = fc.showOpenDialog(Globals.getMainFrame());
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File f = fc.getSelectedFile();
        if (f != null) {

            String sql = null;//from  w  w w .j  a v a  2  s.c  o m
            String entityName = null;
            Object entity = null;
            FileInputStream fis = null;
            entityName = f.getName();
            try {
                XStream xstream = XStreamFactory.createXStream();
                fis = new FileInputStream(f);
                entity = xstream.fromXML(fis);

            } catch (Exception ex) {
                Show.error(ex);
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
            }

            if (entityName.endsWith(QueryFilter.QUERY_EXTENSION)
                    || entityName.endsWith(ReportFilter.REPORT_EXTENSION)) {

                Report report = (Report) entity;
                if (report.getSql() != null) {
                    sql = report.getSql();
                } else if (report.getQuery() != null) {
                    SelectQuery query = report.getQuery();
                    try {
                        query.setDialect(DialectUtil.getDialect(Globals.getConnection()));
                    } catch (Exception ex) {
                        ex.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                        LOG.error(ex.getMessage(), ex);
                    }
                    sql = query.toString();
                }

            } else if (entityName.endsWith(ChartFilter.CHART_EXTENSION)) {
                Chart chart = (Chart) entity;
                if (chart.getReport().getSql() != null) {
                    sql = chart.getReport().getSql();
                } else if (chart.getReport().getQuery() != null) {
                    SelectQuery query = chart.getReport().getQuery();
                    try {
                        query.setDialect(DialectUtil.getDialect(Globals.getConnection()));
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        LOG.error(ex.getMessage(), ex);
                    }
                    sql = query.toString();
                }
            }

            Editor editor = new Editor();
            editor.setText(sql);
            editor.setPreferredSize(new Dimension(400, 400));
            JFrame frame = new JFrame(I18NSupport.getString("view.sql.info", entityName));
            frame.setIconImage(ImageUtil.getImageIcon("report_view").getImage());
            frame.setLayout(new GridBagLayout());
            frame.add(editor, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
                    GridBagConstraints.BOTH, new Insets(10, 10, 10, 10), 0, 0));
            frame.pack();
            Show.centrateComponent(Globals.getMainFrame(), frame);
            frame.setVisible(true);

        }
    }

}

From source file:ru.gelin.fictionbook.reader.actions.OpenAction.java

/**
 *  Shows file chosing dialog and returns choosed file or null if
 *  file was not selected.//from  w  w  w .j  a v a 2  s  .c o m
 */
File chooseFile() {
    File result = null;
    JFileChooser chooser = new JFileChooser();
    if (currentDirectory != null) {
        chooser.setCurrentDirectory(currentDirectory);
    }
    chooser.addChoosableFileFilter(new FBFileFilter());
    int returnValue = chooser.showOpenDialog(getParentComponent());
    if (returnValue == JFileChooser.APPROVE_OPTION) {
        result = chooser.getSelectedFile();
        if (log.isInfoEnabled()) {
            log.info(result + " file is selected");
        }
    }
    currentDirectory = chooser.getCurrentDirectory(); //save current dialog directory
    return result;
}

From source file:terminotpad.MainFrame.java

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
    // TODO add your handling code here:
    String content;// ww  w.j a v  a  2  s  .  co m
    String destFile;
    int ext = 0;
    content = rSyntax.getText();
    //    destFile = "src/doc/test.txt";
    while (ext == 0) {
        JFileChooser dlg = new JFileChooser();
        dlg.addChoosableFileFilter(new MessageFilter());
        dlg.setDialogType(javax.swing.JFileChooser.SAVE_DIALOG);
        dlg.setDialogTitle("Enregistrer sous ...");
        int ret = dlg.showOpenDialog(this);
        File fileReturn;
        // Traite le contenu du fichier
        if (ret == JFileChooser.APPROVE_OPTION) {
            fileReturn = dlg.getSelectedFile();
            destFile = fileReturn.toString();
            System.out.println(destFile);
            Fichier file = new Fichier(destFile, content);
            file.fileWrite();

            String reg = "[.][a-zA-Z0-9]{3}$";
            if (file.getExtend().matches(reg)) {
                ext = 1;
            }
            localFile.setFile(file.getFile());
        }
    }
}

From source file:ui.UI.java

private void jButtonInputFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonInputFileActionPerformed
    JFileChooser chooser = new JFileChooser(new File("."));
    FileFilter filter = new FileNameExtensionFilter("Video Files", "mp4", "mp2");
    chooser.addChoosableFileFilter(filter);
    chooser.setFileFilter(filter);// w  ww  .  ja va2s  .c  om
    int choice = chooser.showOpenDialog(null);

    if (choice == JFileChooser.APPROVE_OPTION) {
        toddler.setInputFile(chooser.getSelectedFile());
    }
}

From source file:unikn.dbis.univis.explorer.VExplorer.java

License:asdf

private void initMenuBar() {

    JMenuBar menuBar = new JMenuBar();

    VMenu program = new VMenu(Constants.PROGRAM);

    VMenuItem schemaImport = new VMenuItem(Constants.SCHEMA_IMPORT, VIcons.SCHEMA_IMPORT);
    schemaImport.setAccelerator(KeyStroke.getKeyStroke('I', Event.CTRL_MASK));
    schemaImport.addActionListener(new ActionListener() {
        /**/*from   w  ww  . j  a  v  a  2  s  .  c om*/
         * Invoked when an action occurs.
         */
        public void actionPerformed(ActionEvent e) {
            JFileChooser fileChooser = new JFileChooser();

            fileChooser.addChoosableFileFilter(new FileFilter() {

                /**
                 * Whether the given file is accepted by this filter.
                 */
                public boolean accept(File f) {
                    return f.getName().endsWith(".vs.xml") || f.isDirectory();
                }

                /**
                 * The description of this filter. For example: "JPG and GIF Images"
                 *
                 * @see javax.swing.filechooser.FileView#getName
                 */
                public String getDescription() {
                    return "UniVis Schema (*.vs.xml)";
                }
            });

            int option = fileChooser.showOpenDialog(VExplorer.this);

            if (option == JFileChooser.APPROVE_OPTION) {
                File file = fileChooser.getSelectedFile();
                new SchemaImport(file);
                refreshTree();
                JOptionPane.showMessageDialog(VExplorer.this, "Schema Import erfolgreich beendet.",
                        "Schema Import", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    });
    program.add(schemaImport);
    program.addSeparator();

    VMenuItem exit = new VMenuItem(Constants.EXIT, VIcons.EXIT);
    exit.setAccelerator(KeyStroke.getKeyStroke('Q', Event.ALT_MASK));
    exit.addActionListener(new ActionListener() {
        /**
         * Invoked when an action occurs.
         */
        public void actionPerformed(ActionEvent e) {
            System.exit(0);
        }
    });
    program.add(exit);

    VMenu lafMenu = new VMenu(Constants.LOOK_AND_FEEL);

    ButtonGroup lafGroup = new ButtonGroup();
    for (final UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
        JRadioButtonMenuItem lafMenuItem = new JRadioButtonMenuItem(laf.getName());

        // Set the current Look And Feel as selected.
        if (UIManager.getLookAndFeel().getName().equals(laf.getName())) {
            lafMenuItem.setSelected(true);
        }

        lafMenuItem.addActionListener(new ActionListener() {
            /**
             * Invoked when an action occurs.
             */
            public void actionPerformed(ActionEvent e) {
                updateLookAndFeel(laf.getClassName());
            }
        });

        lafGroup.add(lafMenuItem);
        lafMenu.add(lafMenuItem);
    }

    JMenu questionMark = new JMenu("?");

    VMenuItem license = new VMenuItem(Constants.LICENSE);
    license.addActionListener(new ActionListener() {

        /**
         * {@inheritDoc}
         */
        public void actionPerformed(ActionEvent e) {
            new LicenseDialog(VExplorer.this);
        }
    });
    questionMark.add(license);

    final VMenuItem about = new VMenuItem(Constants.ABOUT, VIcons.INFORMATION);
    about.addActionListener(new ActionListener() {

        /**
         * {@inheritDoc}
         */
        public void actionPerformed(ActionEvent e) {
            new AboutPanel(VExplorer.this);
        }
    });
    questionMark.add(about);

    menuBar.add(program);
    menuBar.add(lafMenu);
    menuBar.add(questionMark);

    setJMenuBar(menuBar);
}

From source file:us.daveread.basicquery.BasicQuery.java

/**
 * Open or create a SQL statement file./*from  ww w.  j a  v  a2s.  c  om*/
 */
private void openSQLFile() {
    JFileChooser fileMenu;
    FileFilter defaultFileFilter = null;
    FileFilter preferredFileFilter = null;
    File chosenSQLFile;
    int returnVal;

    chosenSQLFile = null;

    // Save current information, including SQL Statements
    saveConfig();

    // Allow user to choose/create new file for SQL Statements
    fileMenu = new JFileChooser(new File(queryFilename));

    for (FileFilterDefinition filterDefinition : FileFilterDefinition.values()) {
        if (filterDefinition.name().startsWith("QUERY")) {
            final FileFilter fileFilter = new SuffixFileFilter(filterDefinition.description(),
                    filterDefinition.acceptedSuffixes());
            if (filterDefinition.isPreferredOption()) {
                preferredFileFilter = fileFilter;
            }
            fileMenu.addChoosableFileFilter(fileFilter);
            if (filterDefinition.description().equals(latestChosenQueryFileFilterDescription)) {
                defaultFileFilter = fileFilter;
            }
        }
    }

    if (defaultFileFilter != null) {
        fileMenu.setFileFilter(defaultFileFilter);
    } else if (latestChosenQueryFileFilterDescription != null
            && latestChosenQueryFileFilterDescription.startsWith("All")) {
        fileMenu.setFileFilter(fileMenu.getAcceptAllFileFilter());
    } else if (preferredFileFilter != null) {
        fileMenu.setFileFilter(preferredFileFilter);
    }

    fileMenu.setSelectedFile(new File(queryFilename));
    fileMenu.setDialogTitle(Resources.getString("dlgSQLFileTitle"));
    fileMenu.setDialogType(JFileChooser.OPEN_DIALOG);
    fileMenu.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fileMenu.setMultiSelectionEnabled(false);

    if (fileMenu.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        chosenSQLFile = fileMenu.getSelectedFile();

        // Adjust file suffix if necessary
        final FileFilter fileFilter = fileMenu.getFileFilter();
        if (fileFilter != null && fileFilter instanceof SuffixFileFilter
                && !fileMenu.getFileFilter().accept(chosenSQLFile)) {
            chosenSQLFile = ((SuffixFileFilter) fileFilter).makeWithPrimarySuffix(chosenSQLFile);
        }

        if (!chosenSQLFile.exists()) {
            returnVal = JOptionPane.showConfirmDialog(this,
                    Resources.getString("dlgNewSQLFileText", chosenSQLFile.getName()),
                    Resources.getString("dlgNewSQLFileTitle"), JOptionPane.YES_NO_CANCEL_OPTION,
                    JOptionPane.QUESTION_MESSAGE);
            if (returnVal == JOptionPane.NO_OPTION) {
                querySelection.removeAllItems();
                queryText.setText("");
                QueryHistory.getInstance().clearAllQueries();

                // Update GUI
                setPrevNextIndication();
            } else if (returnVal == JOptionPane.CANCEL_OPTION) {
                chosenSQLFile = null;
            }
        } else {
            setQueryFilename(chosenSQLFile.getAbsolutePath());
            querySelection.removeAllItems();
            queryText.setText("");
            loadCombo(querySelection, queryFilename);
            QueryHistory.getInstance().clearAllQueries();

            // Update GUI
            setPrevNextIndication();
        }
    }

    try {
        latestChosenQueryFileFilterDescription = fileMenu.getFileFilter().getDescription();
    } catch (Throwable throwable) {
        LOGGER.warn("Unable to determine which ontology file filter was chosen", throwable);
    }

    if (chosenSQLFile != null) {
        setQueryFilename(chosenSQLFile.getAbsolutePath());
        saveConfig();
    }
}

From source file:View.Main.java

private void jButton_loadImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_loadImageActionPerformed
    // TODO add your handling code here: 
    jLabel_status.setText(" ");
    JFileChooser fc = new JFileChooser();
    Double rating;//from   w w  w  . j a v  a 2 s .  c o m
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    fc.addChoosableFileFilter(new FileNameExtensionFilter("JPEG files", "jpeg", "jpg"));
    fc.addChoosableFileFilter(new FileNameExtensionFilter("PNG files", "png", "PNG"));
    fc.addChoosableFileFilter(new FileNameExtensionFilter("BMP files", "bmp", "BMP"));
    fc.setAcceptAllFileFilterUsed(true);
    int returnVal = fc.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        imagePath = fc.getSelectedFile().getAbsolutePath();
        rating = imageAnalizer.getRating(imagePath);
        setTextRating(rating);
        populateProgressBar(rating);
        try {
            setImage(imagePath);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Please select an image of valid format", "Error",
                    JOptionPane.WARNING_MESSAGE);
            //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        getNews(rating);

    }
    //        else {
    //            JOptionPane.showMessageDialog(null, "Please select an image of valid format", "Error", JOptionPane.WARNING_MESSAGE);
    //        }    
}

From source file:visolate.Visolate.java

private File browse() {
    try {/*from  ww  w . j  ava  2 s  . co  m*/
        File input = null;
        String[] zenity = { "zenity", "--file-selection", "--title=Open", "--file-filter=Gerber file | *.gbr",
                "--file-filter=All | * " }; //FIXME: dirty workaround to get a fully functional and native file dialog on linux
        String filestring;
        try {
            Process p = Runtime.getRuntime().exec(zenity);
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            StringBuffer sb = new StringBuffer();

            sb.append(br.readLine());
            filestring = sb.toString();
            if (filestring.equals("null")) {
                return null;
            }
            input = new File(filestring);

        } catch (IOException e1) { //fallback if zenity is not installed
            final JFileChooser fc = new JFileChooser();
            fc.addChoosableFileFilter(new FileFilter() {

                @Override
                public String getDescription() {
                    return "Gerber file";
                }

                @Override
                public boolean accept(File f) {
                    return f.getName().endsWith(".gbr");
                }
            });

            int returnVal = -1;

            returnVal = fc.showOpenDialog(fc);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                input = fc.getSelectedFile();
            }
        }
        return input;
    } catch (AccessControlException e1) {
        accessControlError();
        return null;
    }
}

From source file:xmv.solutions.commons.ExcelFile.java

/**
 * Open a filechooser that finds ExcelFiles
 *
 * @param startPath starting with path startPath
 * @return FilePath// ww w . j a  v  a  2  s.c  o  m
 */
public static ExcelFile openFileChooser(String startPath) {

    // Create a file chooser
    final JFileChooser fc = new JFileChooser();

    fc.setCurrentDirectory(new File(startPath));

    // Remove all FileFilters
    FileFilter[] filters = fc.getChoosableFileFilters();
    for (int i = 0; i < filters.length; i++) {
        fc.removeChoosableFileFilter(filters[i]);
    }

    fc.addChoosableFileFilter(new ExcelFileFilter());

    // In response to a button click:
    int returnVal = fc.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {

        String path = fc.getSelectedFile().getAbsolutePath();
        return new ExcelFile(path);

    }

    return null;

}