在JFileChooser的Windows外觀中,JFileChooser對話框的左側顯示五個按鈕:最近項目,桌面,我的文檔,計算機和網絡。這些代表Windows資源管理器將顯示文件系統的視圖。看起來,除非調用setSelectedFile()或setCurrentDirectory()方法,否則JFileChooser默認爲My Documents View。如何使JFileChooser默認爲計算機視圖而不是我的文檔
我試圖讓用戶選擇一個映射網絡驅動器,它應該出現在「計算機」視圖中。有沒有辦法設置JFileChooser默認打開「計算機」視圖?
我已經嘗試了幾種方法來強制它,最近找到根目錄並將其設置爲currentDirectory,但這顯示了該根節點的內容。最近的代碼包含在下面。
private File originalServerRoot;
private class SelectOriginalUnitServerDriveListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
JFileChooser origDriveChooser = new JFileChooser();
origDriveChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
File startFile = new File(System.getProperty("user.dir")); //Get the current directory
// Find System Root
while (!FileSystemView.getFileSystemView().isFileSystemRoot(startFile))
{
startFile = startFile.getParentFile();
}
origDriveChooser.setCurrentDirectory(startFile);
origDriveChooser.setDialogTitle("Select the Mapped Network Drive");
int origDriveChooserRetVal = origDriveChooser.showDialog(contentPane,"Open");
if (origDriveChooserRetVal == JFileChooser.APPROVE_OPTION)
{
originalUnitServerRoot = origDriveChooser.getSelectedFile();
}
}
}
有沒有可以讓我選擇默認的「計算機」視圖(或網絡,或任何其他視圖)的方法,或以任何方式欺騙JFileChooser中?
編輯
感謝您的快速和徹底的答案。我將Hovercraft Full Of Eels和Guillaume Polet的答案結合起來,嘗試使代碼在任何驅動器盤符上運行。結果代碼如下。再一次,謝謝。
private File originalServerRoot;
private class SelectOriginalUnitServerDriveListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
JFileChooser origDriveChooser = new JFileChooser();
origDriveChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
File startFile = new File(System.getProperty("user.dir")); //Get the current directory
// Find System Root
while (!FileSystemView.getFileSystemView().isFileSystemRoot(startFile))
{
startFile = startFile.getParentFile();
}
//Changed the next line
origDriveChooser.setCurrentDirectory(origDriveChooser.getFileSystemView().getParentDirectory(rootFile));
origDriveChooser.setDialogTitle("Select the Mapped Network Drive");
int origDriveChooserRetVal = origDriveChooser.showDialog(contentPane,"Open");
if (origDriveChooserRetVal == JFileChooser.APPROVE_OPTION)
{
originalUnitServerRoot = origDriveChooser.getSelectedFile();
}
}
}
1+和同上,這也很好。 –