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");
}
Your problem is that:
stop execution of code until user select a file. Add this line after adding
FileFilterand 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 aFileFilteronce againshowOpenDialogit will work as you expect.