Netbeans+-+File+Chooser+Code



Use this code as part of your FileChooser JFrame: Remember the first paragraph goes immediately below your import statements:

class MyCustomFilter extends javax.swing.filechooser.FileFilter { @Override public boolean accept(File file) { // Allow only directories, or files with ".txt" extension return file.isDirectory || file.getAbsolutePath.endsWith(".txt"); } @Override public String getDescription { // This description will be displayed in the dialog, // hard-coded = ugly, should be done via I18N return "Text documents (*.txt)"; } }

And the seond paragraph goes within the Open Action you would have already created:

int returnVal = FileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = FileChooser.getSelectedFile; try { // What to do with the file, e.g. display it in a TextArea textarea.read( new FileReader( file.getAbsolutePath ), null ); }

catch (IOException ex) { System.out.println("problem accessing file"+file.getAbsolutePath); } } else { System.out.println("File access cancelled by user."); }