Example usage for javax.swing JFileChooser getChoosableFileFilters

List of usage examples for javax.swing JFileChooser getChoosableFileFilters

Introduction

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

Prototype

@BeanProperty(bound = false)
public FileFilter[] getChoosableFileFilters() 

Source Link

Document

Gets the list of user choosable file filters.

Usage

From source file:Main.java

public static void main(String[] a) {
    JFrame frame = new JFrame("JFileChooser Popup");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JFileChooser fileChooser = new JFileChooser(".");

    FileFilter[] filters = fileChooser.getChoosableFileFilters();

    frame.add(fileChooser, BorderLayout.CENTER);

    frame.pack();//from   www  .jav  a 2s .  c  o m
    frame.setVisible(true);
}

From source file:org.pgptool.gui.ui.importkey.KeyImporterPm.java

public MultipleFilesChooserDialog getSourceFileChooser() {
    if (sourceFileChooser == null) {
        sourceFileChooser = new MultipleFilesChooserDialog(findRegisteredWindowIfAny(), appProps,
                BROWSE_FOLDER) {/*  w w w  .ja  v a2s .com*/
            @Override
            protected void doFileChooserPostConstruct(JFileChooser ofd) {
                super.doFileChooserPostConstruct(ofd);
                ofd.setDialogTitle(Messages.get("action.importKey"));

                ofd.setAcceptAllFileFilterUsed(false);
                ofd.addChoosableFileFilter(keyFilesFilter);
                ofd.addChoosableFileFilter(ofd.getAcceptAllFileFilter());
                ofd.setFileFilter(ofd.getChoosableFileFilters()[0]);
            }

            private FileFilter keyFilesFilter = new FileFilter() {
                @Override
                public boolean accept(File f) {
                    if (f.isDirectory() || !f.isFile()) {
                        return true;
                    }
                    if (!isExtension(f.getName(), EXTENSIONS)) {
                        return false;
                    }

                    // NOTE: Although it gives best results -- I have a
                    // slight concern that this might be too heavy operation
                    // to perform thorough -- check for each file
                    // contents. My hope is that since we're checking only
                    // key files it shouldn't be a problem. Non-key files
                    // with same xtensions will not take a long time to fail
                    try {
                        Key readKey = keyFilesOperations.readKeyFromFile(f.getAbsolutePath());
                        Preconditions.checkState(readKey != null, "Key wasn't parsed");

                        Key existingKey = keyRingService.findKeyById(readKey.getKeyInfo().getKeyId());
                        if (existingKey == null) {
                            return true;
                        }
                        if (!existingKey.getKeyData().isCanBeUsedForDecryption()
                                && readKey.getKeyData().isCanBeUsedForDecryption()) {
                            return true;
                        }
                        return false;
                    } catch (Throwable t) {
                        // in this case it's not an issue. So it's debug
                        // level
                        log.debug(
                                "File is not accepte for file chooser becasue was not able to read it as a key",
                                t);
                    }

                    return false;
                }

                private boolean isExtension(String fileName, String[] extensions) {
                    String extension = FilenameUtils.getExtension(fileName);
                    if (!StringUtils.hasText(extension)) {
                        return false;
                    }

                    for (String ext : extensions) {
                        if (ext.equalsIgnoreCase(extension)) {
                            return true;
                        }
                    }
                    return false;
                }

                @Override
                public String getDescription() {
                    return "Key files (.asc, .bpg)";
                }
            };
        };
    }
    return sourceFileChooser;
}

From source file:de.juwimm.cms.content.panel.PanDocuments.java

private void upload(String prosa, Integer unit, Integer viewComponentId, Integer documentId) {
    this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    JFileChooser fc = new JFileChooser();
    int ff = fc.getChoosableFileFilters().length;
    FileFilter[] fft = fc.getChoosableFileFilters();
    for (int i = 0; i < ff; i++) {
        fc.removeChoosableFileFilter(fft[i]);
    }//w w  w.ja  va2 s .  co m
    fc.addChoosableFileFilter(new DocumentFilter());
    fc.setAccessory(new ImagePreview(fc));
    fc.setDialogTitle(prosa);
    fc.setMultiSelectionEnabled(true);
    fc.setCurrentDirectory(Constants.LAST_LOCAL_UPLOAD_DIR);
    int returnVal = fc.showDialog(this, Messages.getString("panel.content.documents.addDocument"));

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File[] files = fc.getSelectedFiles();
        uploadFiles(files, unit, viewComponentId, documentId);
        Constants.LAST_LOCAL_UPLOAD_DIR = fc.getCurrentDirectory();
    }
    this.setCursor(Cursor.getDefaultCursor());
}

From source file:org.pgptool.gui.ui.encryptone.EncryptOnePm.java

public ExistingFileChooserDialog getSourceFileChooser() {
    if (sourceFileChooser == null) {
        sourceFileChooser = new ExistingFileChooserDialog(findRegisteredWindowIfAny(), appProps,
                SOURCE_FOLDER) {/*  w ww.ja v a 2  s.c  om*/
            @Override
            protected void doFileChooserPostConstruct(JFileChooser ofd) {
                super.doFileChooserPostConstruct(ofd);
                ofd.setDialogTitle(Messages.get("phrase.selectFileToEncrypt"));

                ofd.setAcceptAllFileFilterUsed(false);
                ofd.addChoosableFileFilter(notEncryptedFiles);
                ofd.addChoosableFileFilter(ofd.getAcceptAllFileFilter());
                ofd.setFileFilter(ofd.getChoosableFileFilters()[0]);
            }

            private FileFilter notEncryptedFiles = new FileFilter() {
                @Override
                public boolean accept(File f) {
                    return !DecryptOnePm.isItLooksLikeYourSourceFile(f.getAbsolutePath());
                }

                @Override
                public String getDescription() {
                    return text("phrase.allExceptEncrypted");
                }
            };
        };
    }
    return sourceFileChooser;
}

From source file:org.pgptool.gui.ui.decryptone.DecryptOnePm.java

public ExistingFileChooserDialog getSourceFileChooser() {
    if (sourceFileChooser == null) {
        sourceFileChooser = new ExistingFileChooserDialog(findRegisteredWindowIfAny(), appProps,
                SOURCE_FOLDER) {// ww  w.  j  a v a2  s  .c o  m
            @Override
            protected void doFileChooserPostConstruct(JFileChooser ofd) {
                super.doFileChooserPostConstruct(ofd);

                ofd.setAcceptAllFileFilterUsed(false);
                ofd.addChoosableFileFilter(
                        new FileNameExtensionFilter("Encrypted files (.gpg, .pgp, .asc)", EXTENSIONS));
                ofd.addChoosableFileFilter(ofd.getAcceptAllFileFilter());
                ofd.setFileFilter(ofd.getChoosableFileFilters()[0]);

                ofd.setDialogTitle(text("phrase.selectFileToDecrypt"));
            }

            @Override
            protected String handleFileWasChosen(String filePathName) {
                if (filePathName == null) {
                    return null;
                }
                sourceFile.setValueByOwner(filePathName);
                return filePathName;
            }
        };
    }
    return sourceFileChooser;
}

From source file:org.pgptool.gui.ui.encryptone.EncryptOnePm.java

public SaveFileChooserDialog getTargetFileChooser() {
    if (targetFileChooser == null) {
        targetFileChooser = new SaveFileChooserDialog(findRegisteredWindowIfAny(), "action.chooseTargetFile",
                "action.choose", appProps, "EncryptionTargetChooser") {
            @Override/*from w  w  w  .  j ava 2  s  .c o m*/
            protected String onDialogClosed(String filePathName, JFileChooser ofd) {
                String ret = super.onDialogClosed(filePathName, ofd);
                if (ret != null) {
                    targetFile.setValueByOwner(ret);
                }
                return ret;
            }

            @Override
            protected void onFileChooserPostConstrct(JFileChooser ofd) {
                ofd.setAcceptAllFileFilterUsed(false);
                ofd.addChoosableFileFilter(new FileNameExtensionFilter("GPG Files (.pgp)", "pgp"));
                // NOTE: Should we support other extensions?....
                ofd.addChoosableFileFilter(ofd.getAcceptAllFileFilter());
                ofd.setFileFilter(ofd.getChoosableFileFilters()[0]);
            }

            @Override
            protected void suggestTarget(JFileChooser ofd) {
                String sourceFileStr = sourceFile.getValue();
                if (StringUtils.hasText(targetFile.getValue())) {
                    use(ofd, targetFile.getValue());
                } else if (encryptionDialogParameters != null
                        && encryptionDialogParameters.getTargetFile() != null) {
                    if (encryptionDialogParameters.getSourceFile().equals(sourceFile.getValue())) {
                        use(ofd, encryptionDialogParameters.getTargetFile());
                    } else {
                        use(ofd, madeUpTargetFileName(sourceFile.getValue(), FilenameUtils
                                .getFullPathNoEndSeparator(encryptionDialogParameters.getTargetFile())));
                    }
                } else if (StringUtils.hasText(sourceFileStr) && new File(sourceFileStr).exists()) {
                    String basePath = FilenameUtils.getFullPathNoEndSeparator(sourceFileStr);
                    ofd.setCurrentDirectory(new File(basePath));
                    ofd.setSelectedFile(new File(madeUpTargetFileName(sourceFileStr, basePath)));
                }
            }

            private void use(JFileChooser ofd, String filePathName) {
                ofd.setCurrentDirectory(new File(FilenameUtils.getFullPathNoEndSeparator(filePathName)));
                ofd.setSelectedFile(new File(filePathName));
            }
        };
    }
    return targetFileChooser;
}

From source file:org.cytoscape.dyn.internal.graphMetrics.SaveChartDialog.java

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if (e.getSource() == cancelButton) {
        this.setVisible(false);
        this.dispose();
    } else if (e.getSource() == saveChartButton) {
        JFileChooser saveFileDialog = new JFileChooser();
        saveFileDialog//  w  w w .j a  v a 2  s .c o m
                .addChoosableFileFilter(new ExtensionFileFilter(".jpeg", ".jpg", "Jpeg images (.jpeg, .jpg)"));
        saveFileDialog.addChoosableFileFilter(
                new ExtensionFileFilter(".png", "Portable Network Graphic images (.png)"));
        saveFileDialog
                .addChoosableFileFilter(new ExtensionFileFilter(".svg", "Scalable Vector Graphics (.svg)"));
        int save = saveFileDialog.showSaveDialog(this);
        if (save == JFileChooser.APPROVE_OPTION) {
            File file = saveFileDialog.getSelectedFile();
            int width = ((SpinnerNumberModel) widthSpinner.getModel()).getNumber().intValue();
            int height = ((SpinnerNumberModel) heightSpinner.getModel()).getNumber().intValue();

            ExtensionFileFilter filter = null;
            try {
                filter = (ExtensionFileFilter) saveFileDialog.getFileFilter();
                if (!filter.hasExtension(file)) {
                    file = filter.appendExtension(file);
                }
            } catch (ClassCastException ex) {
                // Try to infer the type of file by its extension
                FileFilter[] filters = saveFileDialog.getChoosableFileFilters();
                for (int i = 0; i < filters.length; ++i) {
                    if (filters[i] instanceof ExtensionFileFilter) {
                        filter = (ExtensionFileFilter) filters[i];
                        if (filter.hasExtension(file)) {
                            break;
                        }
                        filter = null;
                    }
                }

                if (filter == null) {
                    // Could not infer the type
                    JOptionPane.showMessageDialog(null,
                            "File type not specified!\nWhen giving file name, please also select one of the supported file types.",
                            "Error", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            // Save the chart to the specified file name
            try {
                String ext = filter.getExtension();
                if (ext.equals("jpeg")) {
                    ChartUtilities.saveChartAsJPEG(file, chart, width, height);
                } else if (ext.equals("png")) {
                    ChartUtilities.saveChartAsPNG(file, chart, width, height);
                } else {
                    VectorGraphics graphics = new SVGGraphics2D(file, new Dimension(width, height));
                    graphics.startExport();
                    chart.draw(graphics, new Rectangle2D.Double(0, 0, width, height));
                    graphics.endExport();
                }
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "An error occurred while creating or writing to the file.",
                        "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            this.setVisible(false);
            this.dispose();
        } else if (save == JFileChooser.ERROR_OPTION) {
            JOptionPane.showMessageDialog(null, "An error occurred while initializing the window.", "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:app.RunApp.java

/**
 * Save heatmap graph as image//from  w w w  .ja  v  a 2  s.  com
 * 
 * @throws AWTException
 * @throws IOException 
 */
private void saveHeatmapGraph() throws AWTException, IOException {
    BufferedImage image = new Robot().createScreenCapture(
            new Rectangle(panelHeatmap.getLocationOnScreen().x + 31, panelHeatmap.getLocationOnScreen().y + 31,
                    panelHeatmap.getWidth() - 61, panelHeatmap.getHeight() - 61));
    JFileChooser fc = new JFileChooser();

    FileNameExtensionFilter fname1 = new FileNameExtensionFilter(".png", "png");

    fc.removeChoosableFileFilter(fc.getChoosableFileFilters()[0]);

    fc.setFileFilter(fname1);
    fc.addChoosableFileFilter(fname1);

    int returnVal = fc.showSaveDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = new File(fc.getSelectedFile().getAbsolutePath() + ".png");
        ImageIO.write(image, "png", file);

        JOptionPane.showMessageDialog(null, "File saved.", "Successful", JOptionPane.INFORMATION_MESSAGE);
        Toolkit.getDefaultToolkit().beep();
    }
}

From source file:app.RunApp.java

/**
 * Save co-ocurrence graph as image/*from   ww  w .  j av  a  2 s.c o  m*/
 * 
 * @throws AWTException
 * @throws IOException 
 */
private void saveCoocurrenceGraph() throws AWTException, IOException {
    BufferedImage image = new Robot().createScreenCapture(new Rectangle(
            panelCoOcurrenceRight.getLocationOnScreen().x, panelCoOcurrenceRight.getLocationOnScreen().y,
            panelCoOcurrenceRight.getWidth(), panelCoOcurrenceRight.getHeight()));

    JFileChooser fc = new JFileChooser();

    FileNameExtensionFilter fname1 = new FileNameExtensionFilter(".png", "png");

    fc.removeChoosableFileFilter(fc.getChoosableFileFilters()[0]);

    fc.setFileFilter(fname1);
    fc.addChoosableFileFilter(fname1);

    int returnVal = fc.showSaveDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = new File(fc.getSelectedFile().getAbsolutePath() + ".png");

        ImageIO.write(image, "png", file);

        JOptionPane.showMessageDialog(null, "File saved.", "Successful", JOptionPane.INFORMATION_MESSAGE);
        Toolkit.getDefaultToolkit().beep();
    }
}

From source file:app.RunApp.java

/**
 * Action of Save table button in MVML tab
 * //w ww  .j  a  v a 2  s.  c o  m
 * @param evt Event
 */
private void buttonSaveTableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSaveTableActionPerformed
    if (jTable2.getRowCount() == 0 || dataset == null) {
        JOptionPane.showMessageDialog(null, "The table is empty.", "Error", JOptionPane.ERROR_MESSAGE);
        return;
    }

    JFileChooser fc = new JFileChooser();

    //FileNameExtensionFilter fname = new FileNameExtensionFilter(".xls", "xls"); 
    FileNameExtensionFilter fname1 = new FileNameExtensionFilter(".csv", "csv");

    //Remove default
    fc.removeChoosableFileFilter(fc.getChoosableFileFilters()[0]);

    fc.setFileFilter(fname1);

    int returnVal = fc.showSaveDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        FileFilter f1 = fc.getFileFilter();

        if (f1.getDescription().equals(".csv")) {
            try {
                String path = file.getAbsolutePath() + ".csv";

                BufferedWriter bw = new BufferedWriter(new FileWriter(path));
                PrintWriter wr = new PrintWriter(bw);

                ResultsIOUtils.saveMVTableCsv(wr, jTable2, views, dataset);

                wr.close();
                bw.close();

                JOptionPane.showMessageDialog(null, "File saved.", "Successful",
                        JOptionPane.INFORMATION_MESSAGE);
            } catch (IOException | HeadlessException e1) {
                JOptionPane.showMessageDialog(null, "File not saved correctly.", "Error",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}