KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > snow > utils > gui > FileChooserFilter


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 /** can be used in accessory panels.
11     installs a filefilter, take eventual already installed filefilter in account !
12 */

13 public class FileChooserFilter extends JPanel
14 {
15   JTextField searchField = new JTextField(4);
16
17   final JFileChooser fileChooser;
18   // may be null
19
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     // direct search:
31
KeyAdapter kad = new KeyAdapter()
32     {
33       public void keyReleased(KeyEvent ee)
34       {
35         filterAction();
36       }
37     };
38     searchField.addKeyListener( kad );
39
40   } // Constructor
41

42   private void filterAction()
43   {
44      if(filteredFilter==null)
45      {
46        filteredFilter = new FileFilter()
47        {
48          public String JavaDoc getDescription()
49          {
50            if(originalFilter!=null) { return "Filtered "+originalFilter.getDescription(); }
51            return "Filtered files";
52          }
53
54          public boolean accept(java.io.File JavaDoc f)
55          {
56             // don't accept files also refused from original
57
if(originalFilter!=null) { if(!originalFilter.accept(f)) return false; }
58             String JavaDoc nameLow = f.getName().toLowerCase();
59             String JavaDoc 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 JavaDoc[] a)
73   {
74     JFileChooser fs = new JFileChooser();
75     FileChooserFilter fsf = new FileChooserFilter(fs);
76     fs.setAccessory(fsf);
77     //fs.setFileFilter(
78
fs.showOpenDialog(null);
79   }
80
81
82 } // FileChooserFilter
Popular Tags