Adding a Filter to a File Chooser Dialog - Java Swing

Java examples for Swing:JFileChooser

Description

Adding a Filter to a File Chooser Dialog

Demo Code


import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JFrame;

public class Main {

  public void main(String[] argv) {
    JFileChooser fileChooser = new JFileChooser(new File("filename"));
    fileChooser.addChoosableFileFilter(new MyFilter());

    // Open file dialog.
    fileChooser.showOpenDialog(new JFrame());
    System.out.println(fileChooser.getSelectedFile());
  }//from   ww w  . ja  v a2s . c  o m
}

class MyFilter extends javax.swing.filechooser.FileFilter {
  public boolean accept(File file) {
    String filename = file.getName();
    return filename.endsWith(".java");
  }

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

Related Tutorials