2011年8月25日

檔案瀏覽鈕 JFileChooser

參考資料:http://tw.myblog.yahoo.com/209157/article?mid=29
JButton jb= new JButton("開啟檔案");
 String data;//存放檔案位置
 jb.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent ae) {
         JFileChooser chooser = new JFileChooser();
         chooser.setMultiSelectionEnabled(false);
         chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
         chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
         if (chooser.showOpenDialog(getContentPane()) == JFileChooser.APPROVE_OPTION) {
              data = (chooser.getSelectedFile().getAbsolutePath());
              System.out.println(data);//抓取的檔案
          }
     }
 }

傳回選擇的目錄
使用JFileChooser的setFileSelectionMode的JFileChooser.DIRECTORIES_ONLY
參考資料:http://www.lslnet.com/linux/f/docs1/i15/big5176667.htm
JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.showOpenDialog(this);
    //File file = chooser.getSelectedFile();
    //System.out.print(file.getPath());
    System.out.print(chooser.getSelectedFile().toString());

沒有留言:

張貼留言