I have a function openFileAction() that is called when I click the 'File' > 'Open' option in my JMenuBar. Its first lines look like this:
private static String myPath = ... // some path
private void openFileAction() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(myPath));
if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
File f = null;
try {
fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
fileChooser.setFileFilter(new FileNameExtensionFilter(null, ".txt");
f = fileChooser.getSelectedFile();
...
I only want to see .txt files as suggestions -- so I call setFileFilter() on my fileChooser.
This works fine for the directory fileChooser is set to, myPath -- i.e., in the 'Open' pop-up window that appears, I see only .txt files (and folders) in that directory. However, if I navigate away from myPath in the pop-up window, let's say to Desktop, I see all files (and folders) there, and no longer only the .txt files, as I would like to.
How can I see only .txt files in any directory I navigate to?
First, configure the dialog the way you want it, before you show it, so, instead of...
You should be doing something more like...
Second, configure the
FileFiltercorrectly. You should be giving it some kind of "description", as this get's presented to the user and you don't need the.in the extension, instead, it should be more like...Runnable example...
I'd also consider taking a closer look at How to Use File Choosers