1 package snow.utils.gui; 2 3 import javax.swing.*; 4 import javax.swing.event.*; 5 import javax.swing.filechooser.*; 6 import java.awt.*; 7 import java.awt.event.*; 8 import java.util.*; 9 10 13 public class FileChooserFilter extends JPanel 14 { 15 JTextField searchField = new JTextField(4); 16 17 final JFileChooser fileChooser; 18 private final FileFilter originalFilter; 20 private FileFilter filteredFilter; 21 22 public FileChooserFilter(final JFileChooser fileChooser) 23 { 24 this.originalFilter = fileChooser.getFileFilter(); 25 this.fileChooser = fileChooser; 26 27 add(new JLabel("Filter: ")); 28 add(searchField); 29 30 KeyAdapter kad = new KeyAdapter() 32 { 33 public void keyReleased(KeyEvent ee) 34 { 35 filterAction(); 36 } 37 }; 38 searchField.addKeyListener( kad ); 39 40 } 42 private void filterAction() 43 { 44 if(filteredFilter==null) 45 { 46 filteredFilter = new FileFilter() 47 { 48 public String getDescription() 49 { 50 if(originalFilter!=null) { return "Filtered "+originalFilter.getDescription(); } 51 return "Filtered files"; 52 } 53 54 public boolean accept(java.io.File f) 55 { 56 if(originalFilter!=null) { if(!originalFilter.accept(f)) return false; } 58 String nameLow = f.getName().toLowerCase(); 59 String toSearch = searchField.getText().trim().toLowerCase(); 60 if(toSearch.length()==0) return true; 61 if(nameLow.indexOf(toSearch)==-1) return false; 62 return true; 63 } 64 }; 65 66 fileChooser.setFileFilter( filteredFilter ); 67 } 68 fileChooser.rescanCurrentDirectory(); 69 } 70 71 72 public static void main(String [] a) 73 { 74 JFileChooser fs = new JFileChooser(); 75 FileChooserFilter fsf = new FileChooserFilter(fs); 76 fs.setAccessory(fsf); 77 fs.showOpenDialog(null); 79 } 80 81 82 } | Popular Tags |