Tôi muốn giới hạn người dùng của mình vào một thư mục và các thư mục con của nó nhưng nút "Thư mục chính" cho phép họ duyệt đến một thư mục tùy ý.Làm cách nào để hạn chế JFileChooser vào một thư mục?
Tôi nên làm như thế nào?
Tôi muốn giới hạn người dùng của mình vào một thư mục và các thư mục con của nó nhưng nút "Thư mục chính" cho phép họ duyệt đến một thư mục tùy ý.Làm cách nào để hạn chế JFileChooser vào một thư mục?
Tôi nên làm như thế nào?
Bạn có thể làm điều này bằng cách đặt FileSystemView của riêng mình.
Trong trường hợp bất cứ ai khác cần này trong tương lai:
class DirectoryRestrictedFileSystemView extends FileSystemView
{
private final File[] rootDirectories;
DirectoryRestrictedFileSystemView(File rootDirectory)
{
this.rootDirectories = new File[] {rootDirectory};
}
DirectoryRestrictedFileSystemView(File[] rootDirectories)
{
this.rootDirectories = rootDirectories;
}
@Override
public File createNewFolder(File containingDir) throws IOException
{
throw new UnsupportedOperationException("Unable to create directory");
}
@Override
public File[] getRoots()
{
return rootDirectories;
}
@Override
public boolean isRoot(File file)
{
for (File root : rootDirectories) {
if (root.equals(file)) {
return true;
}
}
return false;
}
}
Bạn sẽ rõ ràng là cần phải thực hiện một "createNewFolder" phương pháp tốt hơn, nhưng điều này không hạn chế người sử dụng một trong nhiều thư mục.
Và sử dụng nó như thế này:
FileSystemView fsv = new DirectoryRestrictedFileSystemView(new File("X:\\"));
JFileChooser fileChooser = new JFileChooser(fsv);
hay như thế này:
FileSystemView fsv = new DirectoryRestrictedFileSystemView(new File[] {
new File("X:\\"),
new File("Y:\\")
});
JFileChooser fileChooser = new JFileChooser(fsv);
Không hoạt động @Allain –
Các giải pháp của Allain là gần như hoàn tất. Ba vấn đề được mở để giải quyết:
public TFile getHomeDirectory() { return rootDirectories[0]; }
bộ lớp và constructor public
Thay đổi JFileChooser fileChooser = new JFileChooser(fsv);
vào JFileChooser fileChooser = new JFileChooser(fsv.getHomeDirectory(),fsv);
tôi sử dụng nó để hạn chế người dùng ở trong một zip-file qua TrueZips TFileChooser và với những sửa đổi nhỏ cho mã trên, điều này hoạt động hoàn hảo. Cảm ơn rất nhiều.
Không cần phải phức tạp như vậy. Bạn có thể dễ dàng thiết lập chế độ lựa chọn một JFileChooser như thế này
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setMultiSelectionEnabled(false);
Bạn có thể đọc thêm tài liệu tham khảo ở đây How to Use File Choosers
Điều này giới hạn chúng vào thư mục nói chung, nhưng không giới hạn đến một thư mục cụ thể, đó là câu hỏi của OP. –
làm thế nào để bạn có được những filesystemview mặc định (ví dụ như để uỷ thác cho nó)? –
@Jonon S - có lẽ thông qua phương thức tĩnh 'getFileSystemView()' – McDowell
Chỉ cần nếu ai đó có thể cần nó, đây là một ví dụ chính xác về những gì OP muốn: http://tips4java.wordpress.com/2009/01/28/single -root-file-chooser/ –