JFileChooser在MAC OS里面的问题

最近遇到一个需求,下载ftp到本地系统,需要打开一个文件保存对话框。本地操作系统要支持windows、linux和mac。所以考虑用java的javax.swing.JFileChooser;

于是,写了个测试程序如下:

 

代码
public static void main(String[] args) {
    String retStr 
= "";
    JFileChooser   c
=new   JFileChooser();   
    c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);   
    c.setDialogTitle(
"请选择下载的目标文件夹");
    c.setDialogType(JFileChooser.SAVE_DIALOG);
    
int ret = c.showSaveDialog(null);
    
if(ret==JFileChooser.CANCEL_OPTION){
        retStr 
= "";
    }
    
else if(ret==JFileChooser.APPROVE_OPTION){
        retStr 
= c.getSelectedFile().getAbsolutePath();
        System.out.println(retStr);
        
//System.out.println(System.getProperty("os.name"));

    }
    
else if(ret==JFileChooser.ERROR_OPTION){
        retStr 
= "";
    }
}

 

 

在windows下运行没有问题,能正常得到保存的文件夹地址,但是到了MAC下,发现奇怪现象,比如如果选中/Volume/ftptest/,并且双击打开,得到的路径将是/Volume/ftptest/ftptest/ ,也就是目标文件夹会重复,但是若直选中文件夹,而不进入,将返回正确路径。。。

 

初步判定是JFileChooser的showSaveDialog对跨平台支持不好,或者是MAC系统对java支持不好。后来遍寻解决方法,在一老外的博客上看到解决办法:

The problem occurs when you use chooser.showDialog or chooser.showSaveDialog instead of chooser.showOpenDialog. On XP chooser.showDialog returns the correct path under the example given by the OP, but on Mac OS 10.5.7 (and probably earlier versions as well) you'll get ~/Desktop/Desktop .

敢情在MAC上不要用showDialog和showSaveDialog。。。。

 

所以,上面代码中showSaveDialog改为showOpenDialog,问题解决。

posted @ 2010-04-27 16:42  MichaelChen  阅读(848)  评论(0编辑  收藏  举报