歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java文件選擇JFileChooser使用例子

Java文件選擇JFileChooser使用例子

日期:2017/3/1 10:37:40   编辑:Linux編程
JFileChooser類的使用非常簡單,主要是對一些屬性的設置,以及文件篩選器的使用。

[java]

  1. import javax.swing.JFileChooser;
  2. public class FileChooser {
  3. public static void main(String[] args)
  4. {
  5. JFileChooser fc = new JFileChooser("D:");
  6. //是否可多選
  7. fc.setMultiSelectionEnabled(false);
  8. //選擇模式,可選擇文件和文件夾
  9. fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
  10. // fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
  11. // fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
  12. //設置是否顯示隱藏文件
  13. fc.setFileHidingEnabled(true);
  14. fc.setAcceptAllFileFilterUsed(false);
  15. //設置文件篩選器
  16. fc.setFileFilter(new MyFilter("java"));
  17. fc.setFileFilter(new MyFilter("zip"));
  18. int returnValue = fc.showOpenDialog(null);
  19. if (returnValue == JFileChooser.APPROVE_OPTION)
  20. {
  21. //fc.getSelectedFile()
  22. //fc.getSelectedFiles()
  23. }
  24. }
  25. }

[java]

  1. import java.io.File;
  2. import javax.swing.filechooser.FileFilter;
  3. public class MyFilter extends FileFilter
  4. {
  5. private String ext;
  6. public MyFilter(String extString)
  7. {
  8. this.ext = extString;
  9. }
  10. public boolean accept(File f) {
  11. if (f.isDirectory()) {
  12. return true;
  13. }
  14. String extension = getExtension(f);
  15. if (extension.toLowerCase().equals(this.ext.toLowerCase()))
  16. {
  17. return true;
  18. }
  19. return false;
  20. }
  21. public String getDescription() {
  22. return this.ext.toUpperCase();
  23. }
  24. private String getExtension(File f) {
  25. String name = f.getName();
  26. int index = name.lastIndexOf('.');
  27. if (index == -1)
  28. {
  29. return "";
  30. }
  31. else
  32. {
  33. return name.substring(index + 1).toLowerCase();
  34. }
  35. }
  36. }
Copyright © Linux教程網 All Rights Reserved