2010-02-12 69 views
4

我想創建一個「瀏覽」按鈕,當用戶「瀏覽」瀏覽按鈕時,他可以從他的硬盤驅動器文件夾中選擇一個位置來保存該文件。這是我的界面設計的一部分,我該怎麼做? 我希望將路徑顯示在瀏覽按鈕旁邊的文本框中。java swing中的jbutton(瀏覽pc文件夾)

回答

4

你應該看看Sun的教程JFileChooser API。這將給你幾乎所有你需要的東西來完成你想要做的事情。

2
... 
public String fileID; 
public JTextField txtField; //Assume this is the text box you placed beside browse button 
public JButton btnBrowse = JButton("Browse"); 

public void actionPerformed(ActionEvent e) 
{ 
    if (e.getSource() == btnBrowse) 
    { 
     chooser = new JFileChooser(new File(System.getProperty("user.home") + "\\Downloads")); //Downloads Directory as default 
     chooser.setDialogTitle("Select Location"); 
     chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); 
     chooser.setAcceptAllFileFilterUsed(false); 

     if (chooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) 
     { 
      fileID = chooser.getSelectedFile().getPath(); 
      txtField.setText(fileID); 
     } 
    } 
} 
...