23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

public class ExtensionFilter extends javax.swing.filechooser.FileFilter {<br />

}<br />

String extension;<br />

String description;<br />

public ExtensionFilter(String extension, String description) {<br />

}<br />

if (extension.indexOf('.') == -1) {<br />

extension = "." + extension;<br />

}<br />

this.extension = extension;<br />

this.description = description;<br />

public boolean accept(File f) {<br />

}<br />

if (f.getName().endsWith(extension)) {<br />

return true;<br />

}<br />

else if (f.isDirectory()) {<br />

return true;<br />

}<br />

return false;<br />

public String getDescription() {<br />

return this.description + "(*" + extension + ")";<br />

}<br />

<strong>Java</strong> I/O<br />

Here's a main() method that tests this class. ExtensionFilter is used in several of the<br />

examples yet to come.<br />

public static void main(String[] args) {<br />

}<br />

JFrame parent = new JFrame(); // never shown<br />

JFileChooser fc = new JFileChooser();<br />

fc.setDialogTitle("Please choose a file: ");<br />

fc.addChoosableFileFilter(new ExtensionFilter("txt", "Text Files"));<br />

fc.addChoosableFileFilter(new ExtensionFilter("java",<br />

"<strong>Java</strong> Source Code"));<br />

fc.addChoosableFileFilter(new ExtensionFilter(".c", "C Source Code"));<br />

fc.addChoosableFileFilter(new ExtensionFilter(".pl",<br />

"Perl Source Code"));<br />

fc.addChoosableFileFilter(new ExtensionFilter(".html", "HTML Files"));<br />

fc.showOpenDialog(parent);<br />

parent.dispose();<br />

// Work around annoying AWT non-daemon thread bug.<br />

System.exit(0);<br />

The Swing source code contains hints that a class like this may be added to a future release of<br />

Swing.<br />

322

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!