2
A
回答
2
您可以通過將PropertyChangeListener
添加到JFileChooser
來完成此操作。在propertyChange()
方法內檢查屬性名稱是否爲JFileChooser.DIRECTORY_CHANGED_PROPERTY
。如果是,只需調用JFileChooser.approveSelection()
方法即可關閉文件選擇器對話框。
注意:由於選擇一個文件夾將自動關閉文件選擇器,在這種情況下,將文件選擇器(用戶)直接指向他/她可以選擇目標文件夾的文件夾很重要。爲此,使用JFileChooser
的構造函數設置初始/當前文件夾(您可以將該文件夾作爲File
或String
傳遞),也可以通過調用JFileChooser.setCurrentDirectory()
將其設置在構造函數之後。
下面是一個完整的例子:
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("test");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(
evt.getPropertyName())) {
System.out.println("DIRECTORY CHANGED");
fc.approveSelection();
}
}
});
int result = fc.showOpenDialog(f);
if (result == JFileChooser.APPROVE_OPTION) {
System.out.println("Chosen folder: " + fc.getSelectedFile());
}
}
});
f.add(b);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
相關問題
- 1. JFileChooser事件
- 2. 更改JFileChooser中的選定文件以響應事件
- 3. Java - JFileChooser&文件大小
- 4. JFileChooser選擇空文件
- 5. JFilechooser的文件名textfield
- 6. jFilechooser顯示文件夾
- 7. 使用JFileChooser打開文件
- 8. JFileChooser類
- 9. Java - JFileChooser圖像
- 10. 更改的JFileChooser
- 11. 在JFileChooser中
- 12. JFileChooser幫助
- 13. Java KeyBindings with JFileChooser
- 14. JFileChooser as JInternalFrame
- 15. JTable中的JFileChooser
- 16. JFileChooser不會死?
- 17. JFileChooser for Python?
- 18. JFileChooser,以打開多個txt文件
- 19. UCanAccess與JFileChooser:「空數據庫文件」
- 20. 如何使用JFileChooser加載文件?
- 21. 在JFileChooser中只打開.xml文件
- 22. Java JFileChooser getAbsoluteFile添加文件擴展名
- 23. 如何使用JFileChooser保存文件?
- 24. 禁用JFileChooser中文件的重命名?
- 25. JFileChooser返回錯誤的文件名?
- 26. JFileChooser上不顯示擴展名文件
- 27. 在另一個組件中嵌入JFileChooser
- 28. JFileChooser - 多個文件過濾器?
- 29. java JFileChooser文件大小過濾器
- 30. JFileChooser,以選擇多個文件的Java