Java中的檔案對話窗(FileDialog,FilenameFilter,JFileChooser,FileFilter)

來源:互聯網
上載者:User

1.FileDialog使用方法:

 FileDialog fd=new FileDialog(new Frame(),"測試",FileDialog.LOAD);
 FilenameFilter ff=new FilenameFilter(){
   public boolean accept(File dir, String name) {
    if (name.endsWith("jpg")){
     return true;
    }
    return false;
   }
  };
  fd.setFilenameFilter(ff);
 fd.setVisible(true);
 System.out.println(fd.getDirectory()+fd.getFile());

但在Windows中FileDialog + FilenameFilter無法正常工作, jdoc的原注釋為:Filename filters do not function in Sun's reference implementation for Microsoft Windows.

2.FileDialog + FilenameFilter可以用JFileChooser + javax.swing.filechooser.FileFilter 來代替,jdoc中的例子如下:

    JFileChooser chooser = new JFileChooser();
    // Note: source for ExampleFileFilter can be found in FileChooserDemo,
    // under the demo/jfc directory in the Java 2 SDK, Standard Edition.
    ExampleFileFilter filter = new ExampleFileFilter();
    filter.addExtension("jpg");
    filter.addExtension("gif");
    filter.setDescription("JPG & GIF Images");
    chooser.setFileFilter(filter);
    int returnVal = chooser.showOpenDialog(parent);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
       System.out.println("You chose to open this file: " +
            chooser.getSelectedFile().getName());
    }

轉應用執行個體:
    JFileChooser filechooser = new JFileChooser();//建立檔案選取器
    filechooser.setCurrentDirectory(new File("."));//設定目前的目錄
    filechooser.setAcceptAllFileFilterUsed(false);
    //顯示所有檔案
    filechooser.addChoosableFileFilter(new javax.swing.filechooser.FileFilter() {
      public boolean accept(File f) {
        return true;
      }
      public String getDescription() {
        return "所有檔案(*.*)";
      }
    });
    //顯示JAVA源檔案
    filechooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
      public boolean accept(File f) { //設定可用的檔案的尾碼名
        if(f.getName().endsWith(".java")||f.isDirectory()){
          return true;
        }
        return false;
      }
      public String getDescription() {
        return "JAVA來源程式(*.java)";
      }
    });
    //可以反覆使用setFileFilter方法設定JFileChooser的選擇類型

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.