Java Reference
In-Depth Information
// to the ExtentionFilter in demo/jfc accompanying the J2SE SDK.
JFileFilter filter = new
new JFileFilter ();
filter . addType ( "java" );
filter . addType ( "class" );
filter . addType ( "jar" );
filter . setDescription ( "Java-related files" );
chooser . addChoosableFileFilter ( filter );
JButton b = new
new JButton ( "Choose file..." );
add ( b );
b . addActionListener ( new
new ActionListener () {
public
public void
void actionPerformed ( ActionEvent e ) {
int
int returnVal = chooser . showOpenDialog ( frame );
iif ( returnVal == JFileChooser . APPROVE_OPTION ) {
File file = chooser . getSelectedFile ();
System . out . println ( "You chose a " +
( file . isFile () ? "file" : "directory" ) +
" named: " + file . getPath ());
} else
else {
System . out . println ( "You did not choose a filesystem object." );
}
}
});
}
public
public static
void main ( String [] args ) {
JFrame f = new
static void
new JFrame ( "JFileChooser Demo" );
f . getContentPane (). add ( new
new JFileChooserDemo ( f ));
f . pack ();
f . setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE );
f . setVisible ( true
true );
}
}
In this example, I set up a FileFilter for Java files. Note that FileFilter exists both in
javax.swing.filechooser and java.io (an older version, not for use here; see Listing a
Directory ) . The javax.swing.filechooser.FileFilter interface has only two methods:
boolean accept(File) and String getDescription( ) . This is enough for a totally
fixed-function file filter: you could hardcode the list of extensions that should be accepted,
for example. The following class is similar in spirit to the ExampleFileFilter included in
the JDK demo directory:
Search WWH ::




Custom Search