Example usage for javax.swing JFileChooser setFileFilter

List of usage examples for javax.swing JFileChooser setFileFilter

Introduction

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

Prototype

@BeanProperty(preferred = true, description = "Sets the File Filter used to filter out files of type.")
public void setFileFilter(FileFilter filter) 

Source Link

Document

Sets the current file filter.

Usage

From source file:de.codesourcery.jasm16.utils.ASTInspector.java

private void setupUI() throws MalformedURLException {
    // editor pane
    editorPane = new JTextPane();
    editorScrollPane = new JScrollPane(editorPane);
    editorPane.addCaretListener(listener);

    editorScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    editorScrollPane.setPreferredSize(new Dimension(400, 600));
    editorScrollPane.setMinimumSize(new Dimension(100, 100));

    final AdjustmentListener adjustmentListener = new AdjustmentListener() {

        @Override//  ww  w. j  a  v  a 2 s  . com
        public void adjustmentValueChanged(AdjustmentEvent e) {
            if (!e.getValueIsAdjusting()) {
                if (currentUnit != null) {
                    doSemanticHighlighting(currentUnit);
                }
            }
        }
    };
    editorScrollPane.getVerticalScrollBar().addAdjustmentListener(adjustmentListener);
    editorScrollPane.getHorizontalScrollBar().addAdjustmentListener(adjustmentListener);

    // button panel
    final JPanel topPanel = new JPanel();

    final JToolBar toolbar = new JToolBar();
    final JButton showASTButton = new JButton("Show AST");
    showASTButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            boolean currentlyVisible = astInspector != null ? astInspector.isVisible() : false;
            if (currentlyVisible) {
                showASTButton.setText("Show AST");
            } else {
                showASTButton.setText("Hide AST");
            }
            if (currentlyVisible) {
                astInspector.setVisible(false);
            } else {
                showASTInspector();
            }

        }
    });

    fileChooser.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final JFileChooser chooser;
            if (lastOpenDirectory != null && lastOpenDirectory.isDirectory()) {
                chooser = new JFileChooser(lastOpenDirectory);
            } else {
                lastOpenDirectory = null;
                chooser = new JFileChooser();
            }

            final FileFilter filter = new FileFilter() {

                @Override
                public boolean accept(File f) {
                    if (f.isDirectory()) {
                        return true;
                    }
                    return f.isFile() && (f.getName().endsWith(".asm") || f.getName().endsWith(".dasm")
                            || f.getName().endsWith(".dasm16"));
                }

                @Override
                public String getDescription() {
                    return "DCPU-16 assembler sources";
                }
            };
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(frame);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File newFile = chooser.getSelectedFile();
                if (newFile.isFile()) {
                    lastOpenDirectory = newFile.getParentFile();
                    try {
                        openFile(newFile);
                    } catch (IOException e1) {
                        statusModel.addError("Failed to read from file " + newFile.getAbsolutePath(), e1);
                    }
                }
            }
        }
    });
    toolbar.add(fileChooser);
    toolbar.add(showASTButton);

    final ComboBoxModel<String> model = new ComboBoxModel<String>() {

        private ICompilerPhase selected;

        private final List<String> realModel = new ArrayList<String>();

        {
            for (ICompilerPhase p : compiler.getCompilerPhases()) {
                realModel.add(p.getName());
                if (p.getName().equals(ICompilerPhase.PHASE_GENERATE_CODE)) {
                    selected = p;
                }
            }
        }

        @Override
        public Object getSelectedItem() {
            return selected != null ? selected.getName() : null;
        }

        private ICompilerPhase getPhaseByName(String name) {
            for (ICompilerPhase p : compiler.getCompilerPhases()) {
                if (p.getName().equals(name)) {
                    return p;
                }
            }
            return null;
        }

        @Override
        public void setSelectedItem(Object name) {
            selected = getPhaseByName((String) name);
        }

        @Override
        public void addListDataListener(ListDataListener l) {
        }

        @Override
        public String getElementAt(int index) {
            return realModel.get(index);
        }

        @Override
        public int getSize() {
            return realModel.size();
        }

        @Override
        public void removeListDataListener(ListDataListener l) {
        }

    };
    comboBox.setModel(model);
    comboBox.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (model.getSelectedItem() != null) {
                ICompilerPhase oldPhase = findDisabledPhase();
                if (oldPhase != null) {
                    oldPhase.setStopAfterExecution(false);
                }
                compiler.getCompilerPhaseByName((String) model.getSelectedItem()).setStopAfterExecution(true);
                try {
                    compile();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }

        private ICompilerPhase findDisabledPhase() {
            for (ICompilerPhase p : compiler.getCompilerPhases()) {
                if (p.isStopAfterExecution()) {
                    return p;
                }
            }
            return null;
        }
    });

    toolbar.add(new JLabel("Stop compilation after: "));
    toolbar.add(comboBox);

    cursorPosition.setSize(new Dimension(400, 15));
    cursorPosition.setEditable(false);

    statusArea.setPreferredSize(new Dimension(400, 100));
    statusArea.setModel(statusModel);

    /**
     * TOOLBAR
     * SOURCE
     * cursor position
     * status area 
     */
    topPanel.setLayout(new GridBagLayout());

    GridBagConstraints cnstrs = constraints(0, 0, GridBagConstraints.HORIZONTAL);
    cnstrs.gridwidth = GridBagConstraints.REMAINDER;
    cnstrs.weighty = 0;
    topPanel.add(toolbar, cnstrs);

    cnstrs = constraints(0, 1, GridBagConstraints.BOTH);
    cnstrs.gridwidth = GridBagConstraints.REMAINDER;
    topPanel.add(editorScrollPane, cnstrs);

    cnstrs = constraints(0, 2, GridBagConstraints.HORIZONTAL);
    cnstrs.gridwidth = GridBagConstraints.REMAINDER;
    cnstrs.weighty = 0;
    topPanel.add(cursorPosition, cnstrs);

    cnstrs = constraints(0, 3, GridBagConstraints.HORIZONTAL);
    cnstrs.gridwidth = GridBagConstraints.REMAINDER;
    cnstrs.weighty = 0;

    final JPanel bottomPanel = new JPanel();
    bottomPanel.setLayout(new GridBagLayout());

    statusArea.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);

    statusArea.addMouseListener(new MouseAdapter() {

        public void mouseClicked(java.awt.event.MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON1) {
                final int row = statusArea.rowAtPoint(e.getPoint());
                StatusMessage message = statusModel.getMessage(row);
                if (message.getLocation() != null) {
                    moveCursorTo(message.getLocation());
                }
            }
        };
    });

    statusArea.setFillsViewportHeight(true);
    statusArea.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    final JScrollPane statusPane = new JScrollPane(statusArea);
    statusPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    statusPane.setPreferredSize(new Dimension(400, 100));
    statusPane.setMinimumSize(new Dimension(100, 20));

    cnstrs = constraints(0, 0, GridBagConstraints.BOTH);
    cnstrs.weightx = 1;
    cnstrs.weighty = 1;
    cnstrs.gridwidth = GridBagConstraints.REMAINDER;
    cnstrs.gridheight = GridBagConstraints.REMAINDER;

    bottomPanel.add(statusPane, cnstrs);

    // setup frame
    frame = new JFrame(
            "DCPU-16 assembler " + Compiler.VERSION + "   (c) 2012 by tobias.gierke@code-sourcery.de");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    final JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topPanel, bottomPanel);
    splitPane.setBackground(Color.WHITE);
    frame.getContentPane().add(splitPane);

    frame.pack();
    frame.setVisible(true);

    splitPane.setDividerLocation(0.9);
}

From source file:cn.pholance.datamanager.common.components.JRViewer.java

void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
    // Add your handling code here:

    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setLocale(this.getLocale());
    fileChooser.updateUI();/*w w w  .  j ava2s  . c o  m*/
    for (int i = 0; i < saveContributors.size(); i++) {
        fileChooser.addChoosableFileFilter(saveContributors.get(i));
    }

    if (saveContributors.contains(lastSaveContributor)) {
        fileChooser.setFileFilter(lastSaveContributor);
    } else if (saveContributors.size() > 0) {
        fileChooser.setFileFilter(saveContributors.get(0));
    }

    if (lastFolder != null) {
        fileChooser.setCurrentDirectory(lastFolder);
    }

    int retValue = fileChooser.showSaveDialog(this);
    if (retValue == JFileChooser.APPROVE_OPTION) {
        FileFilter fileFilter = fileChooser.getFileFilter();
        File file = fileChooser.getSelectedFile();

        lastFolder = file.getParentFile();

        JRSaveContributor contributor = null;

        if (fileFilter instanceof JRSaveContributor) {
            contributor = (JRSaveContributor) fileFilter;
        } else {
            int i = 0;
            while (contributor == null && i < saveContributors.size()) {
                contributor = saveContributors.get(i++);
                if (!contributor.accept(file)) {
                    contributor = null;
                }
            }

            if (contributor == null) {
                contributor = new JRPrintSaveContributor(this.jasperReportsContext, getLocale(),
                        this.resourceBundle);
            }
        }

        lastSaveContributor = contributor;

        try {
            contributor.save(jasperPrint, file);
        } catch (JRException e) {
            if (log.isErrorEnabled()) {
                log.error("Save error.", e);
            }
            JOptionPane.showMessageDialog(this, getBundleString("error.saving"));
        }
    }
}

From source file:domain.Excel.java

private boolean showOpenFileDialog() {

        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("Specify a file to save");
        FileFilter filter1 = new ExtensionFileFilter("XLS", "XLS");

        fileChooser.setFileFilter(filter1);

        int userSelection = fileChooser.showSaveDialog(parent);

        if (userSelection == JFileChooser.APPROVE_OPTION) {
            File fileToSave = fileChooser.getSelectedFile();
            XLSFile = fileToSave.getAbsolutePath() + ".xls";
            System.out.println("Save as file: " + fileToSave.getAbsolutePath());
            return true;
        }// w w w  .  j a  v a 2  s  .  c om
        return false;
    }

From source file:com.xyphos.vmtgen.GUI.java

private String selectVTF() {
    JFileChooser fc = new JFileChooser(txtWorkFolder.getText());
    fc.setAcceptAllFileFilterUsed(false);
    fc.setFileFilter(new FileFilterVTF());
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);

    int result = fc.showOpenDialog(this);
    if (JFileChooser.APPROVE_OPTION == result) {
        String file = fc.getSelectedFile().getName();
        return FilenameUtils.separatorsToUnix(FilenameUtils.concat(basePath, FilenameUtils.getBaseName(file)))
                .replaceFirst("/", "");
    }/*from   w  w  w.j  a va 2  s  . c  om*/

    return null;
}

From source file:canreg.client.gui.dataentry.PDSEditorInternalFrame.java

@Action
public void savePNGAction() {
    if (chart != null) {
        JFileChooser chooser = new JFileChooser();
        FileFilter filter = new FileFilter() {

            @Override/*from  w  ww. j a  v a 2 s  .c o m*/
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().toLowerCase().endsWith("png"); //NOI18N
            }

            @Override
            public String getDescription() {
                return java.util.ResourceBundle
                        .getBundle("canreg/client/gui/dataentry/resources/PDSEditorInternalFrame")
                        .getString("PNG GRAPHICS FILES");
            }
        };
        chooser.setFileFilter(filter);
        int result = chooser.showDialog(this,
                java.util.ResourceBundle
                        .getBundle("canreg/client/gui/dataentry/resources/PDSEditorInternalFrame")
                        .getString("CHOOSE FILENAME"));
        if (result == JFileChooser.APPROVE_OPTION) {
            try {
                File file = chooser.getSelectedFile();
                if (!file.getName().toLowerCase().endsWith("png")) { //NOI18N
                    file = new File(file.getAbsolutePath() + ".png"); //NOI18N
                }
                ChartUtilities.saveChartAsPNG(file, chart, pyramidPanelHolder.getWidth(),
                        pyramidPanelHolder.getHeight());
            } catch (IOException ex) {
                Logger.getLogger(PDSEditorInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:canreg.client.gui.dataentry.PDSEditorInternalFrame.java

@Action
public void saveSVGAction() {
    if (chart != null) {
        JFileChooser svgFileChooser = new JFileChooser();
        FileFilter filter = new FileFilter() {

            @Override/*from  w  ww .jav  a2 s.com*/
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().toLowerCase().endsWith("svg"); //NOI18N
            }

            @Override
            public String getDescription() {
                return java.util.ResourceBundle
                        .getBundle("canreg/client/gui/dataentry/resources/PDSEditorInternalFrame")
                        .getString("SVG GRAPHICS FILES");
            }
        };
        svgFileChooser.setFileFilter(filter);
        int result = svgFileChooser.showDialog(this,
                java.util.ResourceBundle
                        .getBundle("canreg/client/gui/dataentry/resources/PDSEditorInternalFrame")
                        .getString("CHOOSE FILENAME"));
        if (result == JFileChooser.APPROVE_OPTION) {
            try {
                File file = svgFileChooser.getSelectedFile();
                if (!file.getName().toLowerCase().endsWith("svg")) { //NOI18N
                    file = new File(file.getAbsolutePath() + ".svg"); //NOI18N
                }
                canreg.client.analysis.Tools.exportChartAsSVG(chart,
                        new Rectangle(pyramidPanelHolder.getWidth(), pyramidPanelHolder.getHeight()), file);
            } catch (IOException ex) {
                Logger.getLogger(PDSEditorInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:ca.canucksoftware.ipkpackager.IpkPackagerView.java

private File loadFileChooser(boolean dir, FileFilter filter, String text) {
    File result = null;/*from ww w. j  a  v  a 2s  . co  m*/
    JFileChooser fc = new JFileChooser(); //Create a file chooser
    disableNewFolderButton(fc);
    if (text != null) {
        fc.setSelectedFile(new File(text));
    }
    if (dir) {
        fc.setDialogTitle("");
        File lastDir = new File(
                Preferences.userRoot().get("lastDir", fc.getCurrentDirectory().getAbsolutePath()));
        fc.setCurrentDirectory(lastDir);
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (fc.showDialog(null, "Select") == JFileChooser.APPROVE_OPTION) {
            result = fc.getSelectedFile();
            jTextField1.setText(result.getAbsolutePath());
            Preferences.userRoot().put("lastDir", result.getParentFile().getAbsolutePath());
        }
    } else {
        File lastSaved = null;
        File lastSelected = null;
        if (filter != null) {
            fc.setDialogTitle("Save As...");
            lastSaved = new File(
                    Preferences.userRoot().get("lastSaved", fc.getCurrentDirectory().getAbsolutePath()));
            fc.setCurrentDirectory(lastSaved);
            fc.setFileFilter(filter);
        } else {
            fc.setDialogTitle("");
            lastSelected = new File(
                    Preferences.userRoot().get("lastSelected", fc.getCurrentDirectory().getAbsolutePath()));
            fc.setCurrentDirectory(lastSelected);
            fc.setAcceptAllFileFilterUsed(true);
        }
        if (fc.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
            result = fc.getSelectedFile();
            if (lastSaved != null) {
                Preferences.userRoot().put("lastSaved", result.getParentFile().getAbsolutePath());
            }
            if (lastSelected != null) {
                Preferences.userRoot().put("lastSelected", result.getParentFile().getAbsolutePath());
            }
        }
    }
    return result;
}

From source file:ffx.ui.MainPanel.java

/**
 * Prompt the user to select an alternate key file.
 *//*from  w w  w. ja va 2s . c om*/
private void chooseKey() {
    JFileChooser d = MainPanel.resetFileChooser();
    d.setFileFilter(new KeyFileFilter());
    d.setAcceptAllFileFilterUsed(false);
    FFXSystem sys = getHierarchy().getActive();
    if (sys != null) {
        File newCWD = sys.getFile();
        if (newCWD != null && newCWD.getParentFile() != null) {
            d.setCurrentDirectory(newCWD.getParentFile());
        }
    } else {
        return;
    }
    int result = d.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
        File f = d.getSelectedFile();
        sys.setKeyFile(f);
        sys.setKeywords(KeyFilter.open(f));
        getKeywordPanel().loadActive(sys);
    }
}

From source file:com.lfv.lanzius.server.LanziusServer.java

public void menuChoiceLoadExercise() {
    if (isSwapping)
        return;/*from   w w w  . jav a2 s.  c om*/
    log.info("Menu: Load exercise");
    JFileChooser fc = new JFileChooser("data/exercises");
    fc.setDialogTitle("Load exercise...");
    fc.setMultiSelectionEnabled(false);
    fc.setFileFilter(new FileFilter() {
        public boolean accept(File f) {
            return !f.isHidden() && (f.isDirectory() || f.getName().endsWith(".xml"));
        }

        public String getDescription() {
            return "Exercise (*.xml)";
        }
    });

    int returnVal = JFileChooser.APPROVE_OPTION;
    if (Config.SERVER_AUTOLOAD_EXERCISE == null)
        returnVal = fc.showOpenDialog(frame);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        //File file;
        if (Config.SERVER_AUTOLOAD_EXERCISE == null)
            exerciseFile = fc.getSelectedFile();
        else
            exerciseFile = new File(Config.SERVER_AUTOLOAD_EXERCISE);
        log.info("Loading exercise " + exerciseFile);
        if (exerciseFile.exists()) {
            loadExercise(exerciseFile);
        } else
            JOptionPane.showMessageDialog(frame, "Unable to load exercise! File not found!", "Error!",
                    JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.lfv.lanzius.server.LanziusServer.java

private void menuChoiceLoadConfiguration() {
    if (isSwapping)
        return;/*  www.  j a v  a2  s . c o  m*/
    log.info("Menu: Load configuration");
    JFileChooser fc = new JFileChooser("data/configurations");
    fc.setDialogTitle("Load configuration...");
    fc.setMultiSelectionEnabled(false);
    fc.setFileFilter(new FileFilter() {
        public boolean accept(File f) {
            return !f.isHidden() && (f.isDirectory() || f.getName().endsWith(".xml"));
        }

        public String getDescription() {
            return "Configuration (*.xml)";
        }
    });

    int returnVal = JFileChooser.APPROVE_OPTION;
    if (Config.SERVER_AUTOLOAD_CONFIGURATION == null)
        returnVal = fc.showOpenDialog(frame);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file;
        if (Config.SERVER_AUTOLOAD_CONFIGURATION == null)
            file = fc.getSelectedFile();
        else
            file = new File(Config.SERVER_AUTOLOAD_CONFIGURATION);
        log.info("Loading configuration " + file);
        if (file.exists()) {
            if (buildConfigurationDocument(file)) {
                isConfigLoaded = true;
                updateView();
            } else
                JOptionPane.showMessageDialog(frame,
                        "Invalid configuration file! Make sure that all required tags are defined!", "Error!",
                        JOptionPane.ERROR_MESSAGE);
        } else
            JOptionPane.showMessageDialog(frame, "Unable to load configuration! File not found!", "Error!",
                    JOptionPane.ERROR_MESSAGE);
    }
}