Reputation: 94
I wrote a java code having an awt text field and a button, where if I click on the button, I can browse a file using JFileChooser. It needs to check whether the file has ".txt" extension or not.I wrote the code below, but it is not getting verified.
Where am I going wrong? Please help to determine where I am wrong.
try{
final JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
chooser.addChoosableFileFilter(new FileFilter() {
public String getDescription() {
return "*.txt";
}
public boolean accept(File filename)
{
if(filename.getName().endsWith(".txt")){
return true;
}
else{
System.out.println("Browsed dest file extension must be .txt");
return false;
}}
});
catch(Exception ex)
{
JOptionPane.showMessageDialog(f,"Exception occurred");
}
Upvotes: 1
Views: 13201
Reputation: 3863
Your problem is that:
chooser.showOpenDialog(null);
stop execution of code until user select a file. Add this line after adding FileFilter
and eveyrthing should work ok.
Little explanation:
Method showOpenDialog(Component c)
blockexecution of current thread until user action and next line of your code will be executed after the user choose a file. If you invoke after adding a FileFilter
once again showOpenDialog
it will work as you expect.
Upvotes: 6
Reputation: 1237
I would suggest using the @Override
annotation for the accept
method - see this link @Override explained in Oracle Documentation.
Plus, it would be best to use filename.getName().toLowerCase().endsWith(".txt")
instead filename.getName().endsWith(".txt")
to ensure that files with the extension .TXT
will pass the filter as well.
Upvotes: 4