Reputation: 33
I am dealing with this swing component JfileChooser . I am selecting multiple file and then clicked ok . After that if i again open to select the file it is showing me the previous selected file which i dont want . I want previous directory to be maintained but not the previous files .It gives very Bad User experience .
Here is the code Snippet what i have written.
JFileChooser fileopen = new JFileChooser();
private void fileButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fileButtonActionPerformed
fileopen.setMultiSelectionEnabled(true);
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
File[] file = fileopen.getSelectedFiles();
fileText.setText(file[0].getAbsolutePath());
for( int i =1;i < file.length;i++)
{
fileText.append("||");
fileText.append(file[i].getAbsolutePath());
}
}else {
log.info("File access cancelled by user.");
}
}//GEN-LAST:event_fileButtonActionPerformed
I tried with those setcurrentdirecotory and all . Any help will be appreciated.
Upvotes: 1
Views: 502
Reputation: 347194
Either create a new instance of JFileChooser
each time you need it or call setSelectedFiles
and pass it null
So, I had a quick look at the setSelectedFile
and setSelectedFiles
methods and they should be clearing the selection and the "file name" field, but it doesn't seem to be working for me on Mac OS, so it's likely a look and feel issue.
What I tend to do is cheat. I store the last directory value in the Preferences
API, I do this because it's super easy and it also means that the value persists across executions, super helpful. If you don't want to persist it across executions, you could use a Map
or Properties
or some other variable, that's up to you
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("...");
add(btn);
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileopen = new JFileChooser();
String path = Preferences.userNodeForPackage(TestPane.class).get("FileAccess.lastSelectedDirectory", null);
if (path != null) {
File filePath = new File(path);
if (filePath.exists() && filePath.isDirectory()) {
fileopen.setCurrentDirectory(filePath);
}
}
fileopen.setMultiSelectionEnabled(true);
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
File[] file = fileopen.getSelectedFiles();
System.out.println("You selected " + file.length + " files");
Preferences.userNodeForPackage(TestPane.class).put("FileAccess.lastSelectedDirectory", fileopen.getCurrentDirectory().getAbsolutePath());
} else {
System.out.println("File access cancelled by user.");
}
}
});
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
Upvotes: 1