Example usage for java.awt FileDialog setFilenameFilter

List of usage examples for java.awt FileDialog setFilenameFilter

Introduction

In this page you can find the example usage for java.awt FileDialog setFilenameFilter.

Prototype

public synchronized void setFilenameFilter(FilenameFilter filter) 

Source Link

Document

Sets the filename filter for this file dialog window to the specified filter.

Usage

From source file:com.moneydance.modules.features.importlist.io.MacOSDirectoryChooser.java

@Override
void chooseBaseDirectory() {
    System.setProperty("apple.awt.fileDialogForDirectories", "true");
    final FileDialog fileDialog = new FileDialog((Frame) null, this.getLocalizable().getDirectoryChooserTitle(),
            FileDialog.LOAD);/*from  w  w  w . j av a2  s  . com*/
    fileDialog.setModal(true);
    fileDialog.setFilenameFilter(DirectoryValidator.INSTANCE);

    try {
        fileDialog.setDirectory(FileUtils.getUserDirectory().getAbsolutePath());
    } catch (SecurityException e) {
        LOG.log(Level.WARNING, e.getMessage(), e);
    }

    if (this.getBaseDirectory() != null) {
        final File parentDirectory = this.getBaseDirectory().getParentFile();
        if (parentDirectory != null) {
            fileDialog.setDirectory(parentDirectory.getAbsolutePath());
        }
    }
    fileDialog.setVisible(true);
    System.setProperty("apple.awt.fileDialogForDirectories", "false");

    if (fileDialog.getFile() == null) {
        return;
    }

    this.getPrefs()
            .setBaseDirectory(new File(fileDialog.getDirectory(), fileDialog.getFile()).getAbsolutePath());

    LOG.info(String.format("Base directory is %s", this.getPrefs().getBaseDirectory()));
}

From source file:de.freese.base.swing.mac_os_x.MyApp.java

/**
 * @see//from w w w .java  2 s.  c  o  m
 * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
 */
@Override
public void actionPerformed(final ActionEvent e) {
    Object source = e.getSource();

    if (source == this.quitMI) {
        quit();
    } else {
        if (source == this.optionsMI) {
            preferences();
        } else {
            if (source == this.aboutMI) {
                about();
            } else {
                if (source == this.openMI) {
                    // File:Open action shows a FileDialog for loading displayable images
                    FileDialog openDialog = new FileDialog(this);
                    openDialog.setMode(FileDialog.LOAD);
                    openDialog.setFilenameFilter(new FilenameFilter() {
                        /**
                         * @see java.io.FilenameFilter#accept(java.io.File,
                         * java.lang.String)
                         */
                        @Override
                        public boolean accept(final File dir, final String name) {
                            String[] supportedFiles = ImageIO.getReaderFormatNames();

                            for (String supportedFile : supportedFiles) {
                                if (name.endsWith(supportedFile)) {
                                    return true;
                                }
                            }

                            return false;
                        }
                    });

                    openDialog.setVisible(true);
                    String filePath = openDialog.getDirectory() + openDialog.getFile();

                    if (filePath.length() > 0) {
                        loadImageFile(filePath);
                    }
                }
            }
        }
    }
}

From source file:jpad.MainEditor.java

public void openFile_OSX_Nix() {
    isOpen = true;//from   w ww. j a va  2  s  .  c  om
    FilenameFilter awtFilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            String lowercaseName = name.toLowerCase();
            if (lowercaseName.endsWith(".txt"))
                return true;
            else
                return false;
        }
    };
    FileDialog fd = new FileDialog(this, "Open Text File", FileDialog.LOAD);
    fd.setFilenameFilter(awtFilter);
    fd.setVisible(true);
    if (fd.getFile() == null)
        return;
    else
        curFile = fd.getDirectory() + fd.getFile();
    //TODO: actually open the file
    try (FileInputStream inputStream = new FileInputStream(curFile)) {
        String allText = org.apache.commons.io.IOUtils.toString(inputStream);
        mainTextArea.setText(allText);
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(this, ex.getMessage(), "Error While Reading", JOptionPane.ERROR_MESSAGE);
    }
    JRootPane root = this.getRootPane();
    root.putClientProperty("Window.documentFile", new File(curFile));
    root.putClientProperty("Window.documentModified", Boolean.FALSE);
    hasChanges = false;
    hasSavedToFile = true;
    this.setTitle(String.format("JPad - %s", curFile));
    isOpen = false;
}

From source file:br.upe.ecomp.dosa.view.mainwindow.MainWindowActions.java

private void openTestScenario() {
    FileDialog fileopen = new FileDialog(this, "Open Test Scenario", FileDialog.LOAD);
    fileopen.setFilenameFilter(new FilenameFilter() {
        @Override/*from w  w w  .  ja  v  a 2  s  .  c o m*/
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith("xml");
        }
    });

    fileopen.setVisible(true);

    if (fileopen.getFile() != null) {
        filePath = fileopen.getDirectory();
        fileName = fileopen.getFile();

        algorithm = AlgorithmXMLParser.read(filePath, fileName);
        configureTree();
        updateToolBarButtonsState();
        ((CardLayout) panelTestScenario.getLayout()).last(panelTestScenario);
    }
}

From source file:com.awesheet.models.Workbook.java

@Override
public void onMessage(final UIMessage message) {
    switch (message.getType()) {
    case UIMessageType.CREATE_SHEET: {
        addSheet(new Sheet(this, "Sheet " + (newSheetID + 1)));
        break;//  w  ww  .j  av a  2 s.  com
    }

    case UIMessageType.SELECT_SHEET: {
        SelectSheetMessage uiMessage = (SelectSheetMessage) message;
        selectSheet(uiMessage.getSheet());
        break;
    }

    case UIMessageType.DELETE_SHEET: {
        DeleteSheetMessage uiMessage = (DeleteSheetMessage) message;
        removeSheet(uiMessage.getSheet());
        break;
    }

    case UIMessageType.CREATE_BAR_CHART: {
        CreateBarChartMessage uiMessage = (CreateBarChartMessage) message;

        // Get selected cells.
        Cell selectedCells[] = getSelectedSheet().collectSelectedCells();

        BarChart chart = new BarChart(selectedCells);
        chart.setNameX(uiMessage.getXaxis());
        chart.setNameY(uiMessage.getYaxis());
        chart.setTitle(uiMessage.getTitle());

        if (!chart.generateImageData()) {
            UIMessageManager.getInstance().dispatchAction(
                    new ShowPopupAction<MessagePopup>(UIPopupType.MESSAGE_POPUP, new MessagePopup("Error",
                            "Could not create a chart. Please make sure the cells you selected are in the correct format.")));
            break;
        }

        UIMessageManager.getInstance()
                .dispatchAction(new ShowPopupAction<ChartPopup>(UIPopupType.VIEW_CHART_POPUP,
                        new ChartPopup(new Base64().encodeAsString(chart.getImageData()))));

        break;
    }

    case UIMessageType.CREATE_LINE_CHART: {
        CreateLineChartMessage uiMessage = (CreateLineChartMessage) message;

        // Get selected cells.
        Cell selectedCells[] = getSelectedSheet().collectSelectedCells();

        LineChart chart = new LineChart(selectedCells);
        chart.setNameX(uiMessage.getXaxis());
        chart.setNameY(uiMessage.getYaxis());
        chart.setTitle(uiMessage.getTitle());

        if (!chart.generateImageData()) {
            UIMessageManager.getInstance().dispatchAction(
                    new ShowPopupAction<MessagePopup>(UIPopupType.MESSAGE_POPUP, new MessagePopup("Error",
                            "Could not create a chart. Please make sure the cells you selected are in the correct format.")));
            break;
        }

        UIMessageManager.getInstance()
                .dispatchAction(new ShowPopupAction<ChartPopup>(UIPopupType.VIEW_CHART_POPUP,
                        new ChartPopup(new Base64().encodeAsString(chart.getImageData()))));

        break;
    }

    case UIMessageType.SAVE_CHART_IMAGE: {
        final SaveChartImageMessage uiMessage = (SaveChartImageMessage) message;

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {

                byte imageData[] = new Base64().decode(uiMessage.getImageData());

                FileDialog dialog = new FileDialog(MainFrame.getInstance(), "Save Chart Image",
                        FileDialog.SAVE);
                dialog.setFile("*.png");
                dialog.setVisible(true);
                dialog.setFilenameFilter(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return (dir.isFile() && name.endsWith(".png"));
                    }
                });

                String filePath = dialog.getFile();
                String directory = dialog.getDirectory();
                dialog.dispose();

                if (directory != null && filePath != null) {
                    String absolutePath = new File(directory + filePath).getAbsolutePath();

                    if (!FileManager.getInstance().saveFile(absolutePath, imageData)) {
                        UIMessageManager.getInstance()
                                .dispatchAction(new ShowPopupAction<MessagePopup>(UIPopupType.MESSAGE_POPUP,
                                        new MessagePopup("Error", "Could not save chart image.")));
                    }
                }
            }
        });

        break;
    }
    }
}

From source file:jpad.MainEditor.java

public void saveAs_OSX_Nix() {
    String fileToSaveTo = null;/*from   w  w  w .j ava  2s  .com*/
    FilenameFilter awtFilter = new FilenameFilter() {

        @Override
        public boolean accept(File dir, String name) {
            String lowercaseName = name.toLowerCase();
            if (lowercaseName.endsWith(".txt")) {
                return true;
            } else {
                return false;
            }
        }
    };
    FileDialog fd = new FileDialog(this, "Save Text File", FileDialog.SAVE);
    fd.setDirectory(System.getProperty("java.home"));
    if (curFile == null)
        fd.setFile("Untitled.txt");
    else
        fd.setFile(curFile);
    fd.setFilenameFilter(awtFilter);
    fd.setVisible(true);
    if (fd.getFile() != null)
        fileToSaveTo = fd.getDirectory() + fd.getFile();
    else {
        fileToSaveTo = fd.getFile();
        return;
    }

    curFile = fileToSaveTo;
    JRootPane root = this.getRootPane();
    root.putClientProperty("Window.documentFile", new File(curFile));
    hasChanges = false;
    hasSavedToFile = true;
}

From source file:edu.ku.brc.specify.prefs.FormattingPrefsPanel.java

/**
 * Method for enabling a user to choose a toolbar icon.
 * @param appLabel the label used to display the icon.
 * @param clearIconBtn the button used to clear the icon
 *//*from  w  w  w  .  j a  v a 2 s  . co m*/
protected void chooseToolbarIcon(final JLabel appLabel, final JButton clearIconBtn) {
    FileDialog fileDialog = new FileDialog((Frame) UIRegistry.get(UIRegistry.FRAME),
            getResourceString("PREF_CHOOSE_APPICON_TITLE"), FileDialog.LOAD); //$NON-NLS-1$
    fileDialog.setFilenameFilter(new ImageFilter());
    UIHelper.centerAndShow(fileDialog);
    fileDialog.dispose();

    String path = fileDialog.getDirectory();
    if (StringUtils.isNotEmpty(path)) {
        String fullPath = path + File.separator + fileDialog.getFile();
        File imageFile = new File(fullPath);
        if (imageFile.exists()) {
            ImageIcon newIcon = null;
            ImageIcon icon = new ImageIcon(fullPath);
            if (icon.getIconWidth() != -1 && icon.getIconHeight() != -1) {
                if (icon.getIconWidth() > 32 || icon.getIconHeight() > 32) {
                    Image img = GraphicsUtils.getScaledImage(icon, 32, 32, false);
                    if (img != null) {
                        newIcon = new ImageIcon(img);
                    }
                } else {
                    newIcon = icon;
                }
            }

            ImageIcon appIcon;
            if (newIcon != null) {
                appLabel.setIcon(newIcon);
                clearIconBtn.setEnabled(true);
                String imgBufStr = GraphicsUtils.uuencodeImage(newAppIconName, newIcon);
                AppPreferences.getRemote().put(iconImagePrefName, imgBufStr);
                appIcon = newIcon;

            } else {
                appIcon = IconManager.getIcon("AppIcon");
                appLabel.setIcon(appIcon); //$NON-NLS-1$
                clearIconBtn.setEnabled(false);
                AppPreferences.getRemote().remove(iconImagePrefName);
            }

            IconEntry entry = IconManager.getIconEntryByName(INNER_APPICON_NAME);
            entry.setIcon(appIcon);
            if (entry.getIcons().get(IconManager.IconSize.Std32) != null) {
                entry.getIcons().get(IconManager.IconSize.Std32).setImageIcon(appIcon);
            }

            //((FormViewObj)form).getMVParent().set
            form.getValidator().dataChanged(null, null, null);
        }
    }

}

From source file:edu.ku.brc.specify.utilapps.sp5utils.Sp5Forms.java

@SuppressWarnings({ "unchecked" })
private void openXML() {
    FileDialog fileDlg = new FileDialog((Frame) UIRegistry.getTopWindow(), "", FileDialog.LOAD);

    fileDlg.setFilenameFilter(new FilenameFilter() {
        @Override/*from w  ww .  j a v a2  s  .com*/
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".xml");
        }
    });
    fileDlg.setVisible(true);

    String fileName = fileDlg.getFile();
    if (fileName != null) {
        File iFile = new File(fileDlg.getDirectory() + File.separator + fileName);

        XStream xstream = new XStream();
        FormInfo.configXStream(xstream);
        FormFieldInfo.configXStream(xstream);

        try {
            forms = (Vector<FormInfo>) xstream.fromXML(FileUtils.openInputStream(iFile));
            formsTable.setModel(new FormCellModel(forms));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

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

protected void importReport() {
    FileDialog fileDialog = new FileDialog((Frame) UIRegistry.get(UIRegistry.FRAME),
            getResourceString("CHOOSE_WORKBENCH_IMPORT_FILE"), FileDialog.LOAD);
    //Really shouldn't override workbench prefs with report stuff???
    fileDialog.setDirectory(WorkbenchTask.getDefaultDirPath(WorkbenchTask.IMPORT_FILE_PATH));
    fileDialog.setFilenameFilter(new java.io.FilenameFilter() {
        public boolean accept(File dir, String filename) {
            return FilenameUtils.getExtension(filename).equalsIgnoreCase("jrxml");
        }/*from w ww.j a  v a  2 s.  c  o  m*/

    });
    UIHelper.centerAndShow(fileDialog);
    fileDialog.dispose();

    String fileName = fileDialog.getFile();
    String path = fileDialog.getDirectory();
    if (StringUtils.isNotEmpty(path)) {
        AppPreferences localPrefs = AppPreferences.getLocalPrefs();
        localPrefs.put(WorkbenchTask.IMPORT_FILE_PATH, path);
    }

    File file;
    if (StringUtils.isNotEmpty(fileName) && StringUtils.isNotEmpty(path)) {
        file = new File(path + File.separator + fileName);
    } else {
        return;
    }

    if (file.exists()) {
        if (MainFrameSpecify.importJasperReport(file, true, null)) {
            refreshCommands();
        }
        //else -- assume feedback during importJasperReport()
    }
}

From source file:base.BasePlayer.AddGenome.java

@Override
public void mousePressed(MouseEvent e) {

    if (e.getSource() == tree) {

        if (selectedNode != null && selectedNode.toString().contains("Add new refe")) {
            try {
                FileDialog fs = new FileDialog(frame, "Select reference fasta-file", FileDialog.LOAD);
                fs.setDirectory(Main.downloadDir);
                fs.setVisible(true);//  w ww. j a  v  a  2  s. c  o  m
                String filename = fs.getFile();
                fs.setFile("*.fasta;*.fa");
                fs.setFilenameFilter(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return name.toLowerCase().contains(".fasta") || name.toLowerCase().contains(".fa");
                    }
                });
                if (filename != null) {
                    File addfile = new File(fs.getDirectory() + "/" + filename);

                    if (addfile.exists()) {

                        genomeFile = addfile;
                        Main.downloadDir = genomeFile.getParent();
                        Main.writeToConfig("DownloadDir=" + genomeFile.getParent());
                        OutputRunner runner = new OutputRunner(genomeFile.getName().replace(".fasta", "")
                                .replace(".fa", "").replace(".gz", ""), genomeFile, null);
                        runner.createGenome = true;
                        runner.execute();
                    } else {
                        Main.showError("File does not exists.", "Error", frame);
                    }

                }
                if (1 == 1) {
                    return;
                }
                JFileChooser chooser = new JFileChooser(Main.downloadDir);
                chooser.setMultiSelectionEnabled(false);
                chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                chooser.setAcceptAllFileFilterUsed(false);
                MyFilterFasta fastaFilter = new MyFilterFasta();

                chooser.addChoosableFileFilter(fastaFilter);
                chooser.setDialogTitle("Select reference fasta-file");
                if (Main.screenSize != null) {
                    chooser.setPreferredSize(new Dimension((int) Main.screenSize.getWidth() / 3,
                            (int) Main.screenSize.getHeight() / 3));
                }

                int returnVal = chooser.showOpenDialog((Component) this.getParent());

                if (returnVal == JFileChooser.APPROVE_OPTION) {

                    genomeFile = chooser.getSelectedFile();
                    Main.downloadDir = genomeFile.getParent();
                    Main.writeToConfig("DownloadDir=" + genomeFile.getParent());
                    OutputRunner runner = new OutputRunner(
                            genomeFile.getName().replace(".fasta", "").replace(".gz", ""), genomeFile, null);
                    runner.createGenome = true;
                    runner.execute();

                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else if (selectedNode != null && selectedNode.isLeaf()
                && selectedNode.toString().contains("Add new anno")) {
            try {
                FileDialog fs = new FileDialog(frame, "Select annotation gff3/gtf-file", FileDialog.LOAD);
                fs.setDirectory(Main.downloadDir);
                fs.setVisible(true);
                String filename = fs.getFile();
                fs.setFile("*.gff3;*.gtf");
                fs.setFilenameFilter(new FilenameFilter() {
                    public boolean accept(File dir, String name) {
                        return name.toLowerCase().contains(".gff3") || name.toLowerCase().contains(".gtf");
                    }
                });

                if (filename != null) {
                    File addfile = new File(fs.getDirectory() + "/" + filename);

                    if (addfile.exists()) {
                        annotationFile = addfile;
                        Main.downloadDir = annotationFile.getParent();
                        Main.writeToConfig("DownloadDir=" + annotationFile.getParent());
                        OutputRunner runner = new OutputRunner(selectedNode.getParent().toString(), null,
                                annotationFile);
                        runner.createGenome = true;
                        runner.execute();
                    } else {
                        Main.showError("File does not exists.", "Error", frame);
                    }

                }
                if (1 == 1) {
                    return;
                }
                JFileChooser chooser = new JFileChooser(Main.downloadDir);
                chooser.setMultiSelectionEnabled(false);
                chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                chooser.setAcceptAllFileFilterUsed(false);
                MyFilterGFF gffFilter = new MyFilterGFF();

                chooser.addChoosableFileFilter(gffFilter);
                chooser.setDialogTitle("Select annotation gff3-file");
                if (Main.screenSize != null) {
                    chooser.setPreferredSize(new Dimension((int) Main.screenSize.getWidth() / 3,
                            (int) Main.screenSize.getHeight() / 3));
                }
                int returnVal = chooser.showOpenDialog((Component) this.getParent());

                if (returnVal == JFileChooser.APPROVE_OPTION) {

                    annotationFile = chooser.getSelectedFile();
                    Main.downloadDir = annotationFile.getParent();

                    Main.writeToConfig("DownloadDir=" + annotationFile.getParent());
                    OutputRunner runner = new OutputRunner(selectedNode.getParent().toString(), null,
                            annotationFile);
                    runner.createGenome = true;
                    runner.execute();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    if (e.getSource() == genometable) {

        if (new File(".").getFreeSpace()
                / 1048576 < sizeHash.get(genometable.getValueAt(genometable.getSelectedRow(), 0))[0]
                        / 1048576) {
            sizeError.setVisible(true);
            download.setEnabled(false);
            AddGenome.getLinks.setEnabled(false);
        } else {
            sizeError.setVisible(false);
            download.setEnabled(true);
            AddGenome.getLinks.setEnabled(true);
        }
        tree.clearSelection();
        remove.setEnabled(false);
        checkUpdates.setEnabled(false);
    }

}