JFileChooser doesn't work as it should!
Hi.I stumbled over a problem a few days ago and can't see how to resolve it.
I want to use JFileChooser to select folder(not files).So i done the code and everything work but if i select the folder "/home/john/Documents/" JFileChooser return me "/home/john/" if i select "/home/john/Documents/books/" ,JFileChooser return me "/home/john/Documents".The same thing happens for every path i choose:it returns me the upper folder of what i select.
And the funny thing is that if try this codeSelect a directory with a JFileChooser - Real's Java How-to everything works ok but not my code although the difference is not that big.Here is my code :
Code:
import java.awt.Component;
import java.io.File;
import javax.swing.*;
/**
* @author faur
*
*/
public class DirectoryChooser {
/**
*
*/
private static final long serialVersionUID = 1L;
JFileChooser folderBrowse;
private int returnVal;
private String lastLocation;
Component parent;
DirectoryChooser(Component parent,String lastFolder,String title){
lastLocation = lastFolder;
this.parent = parent;
folderBrowse = new JFileChooser(new File(lastFolder));
folderBrowse.setDialogTitle(title);
//choose only directories and disable file filter selection
folderBrowse.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
folderBrowse.setAcceptAllFileFilterUsed(false);
returnVal = folderBrowse.showOpenDialog(parent);
}
public String getDirectory(){
if(returnVal == JFileChooser.APPROVE_OPTION){
System.out.println(folderBrowse.getCurrentDirectory());
return folderBrowse.getCurrentDirectory().toString();
}
else return lastLocation;
}
}
Code:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.GridLayout;
public class GUI extends JFrame implements SwingConstants{
/**
*
*/
private static final long serialVersionUID = 1L;
JButton folderBtn;
JTextField folderTxt;
JLabel jlBrowse;
String lastFolder;
GUI(String title){
super(title);
lastFolder = System.getProperty("user.home");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(1,3,5,5));
init();
}
void init(){
jlBrowse = new JLabel("Path:");
jlBrowse.setHorizontalAlignment(CENTER);
folderTxt = new JTextField(" ");
folderBtn = new JButton("Browse");
folderBtn.addActionListener(new BtnActionListener());
add(jlBrowse); add(folderTxt); add(folderBtn);
pack();
setVisible(true);
}
class BtnActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
DirectoryChooser folderBrowse = new
DirectoryChooser(GUI.this,GUI.this.lastFolder,"Choose directory...");
GUI.this.lastFolder = folderBrowse.getDirectory();
GUI.this.folderTxt.setText(GUI.this.lastFolder);
}
}
}
Please if you have any ideas about what is wrong don't hesitate.I turned the internet upside down but didn't find any resolve.Thanks
Re: JFileChooser doesn't work as it should!
What did you think getCurrentDirectory() does? and why does JFileChooser have a method getSelectedFile()?
db