PDA

Click to See Complete Forum and Search --> : JFileChooser/FileFilter{Resolved}


Dillinger4
May 1st, 2005, 08:16 PM
Anyone know what i might be doing wrong. I can see that when jfc.showOpenDialog(jf); is called all of the files within the current directory are being scanned cause i can see them flying through the dos window, but when i change the extension in the FileDialog the files that come up within the JFileChooser aren't being filtered.

openfile.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
class JavaFilter extends javax.swing.filechooser.FileFilter{
public boolean accept(File file){
String filename = file.getName();
String extension = filename.substring(0, filename.length());
System.out.println(extension);
if(extension.equals(".java")){
return true;
}
return false;
}
public String getDescription() {
return ".java Files";
}
}
JFileChooser jfc = new JFileChooser();
jfc.setFileFilter(new JavaFilter());
jfc.showOpenDialog(jf);
}
});

System_Error
May 2nd, 2005, 05:09 AM
I don't know if this will help, but this is the Filter class I used for my Text Editor, and it works...


import java.io.File;

public class TextFileFilter extends javax.swing.filechooser.FileFilter
{
public boolean accept(File f)
{
// if its a directory show it
if (f.isDirectory())
return true;

//Get the file extention
String extention = getExtention(f);
//Check to see if the extention is equal to "txt" or "text"
if ((extention.equals("txt")) || (extention.equals("text")))
return true;

return false;
}

public String getDescription()
{
return "Text files";
}

/**
Method to get the extention of the file, in lowercase
*/

private String getExtention(File f)
{
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1)
return s.substring(i+1).toLowerCase();
return "";
}
}

Dillinger4
May 2nd, 2005, 10:25 PM
I added the test i > 0 because it seems substring() kept throwing an indexoutofbounds exception for files with no extension.

class JavaFilter extends javax.swing.filechooser.FileFilter{
String extension;
public boolean accept(File file){
if(file.isDirectory()) return false;
String filename = file.getName();
int i = filename.indexOf('.');
if (i > 0){
extension = filename.substring(i);
}
if(extension.equals(".java")){
return true;
}
return false;
}
public String getDescription() {
return ".java files";
}
}

System_Error
May 3rd, 2005, 05:10 AM
And that worked?

Dillinger4
May 3rd, 2005, 06:28 PM
Yeah it works pretty good now. The exception was only being thrown when i browsed on over to my C:\ drive. For some reason i have .java files on C:\ that have no extension.