如何使用JFileChooser保存文件? [英] How to save file using JFileChooser?

查看:169
本文介绍了如何使用JFileChooser保存文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个名为另存为的方法,它将我的应用程序的图像保存到文件中。
我使用JFileChooser让用户选择他们想要的位置来保存文件。
问题是除非用户明确键入文件格式,否则它会保存没有扩展名的文件。
如何在文件类型下拉菜单中使用jpg,png等格式。

I have a method in my application called "Save as" which Saves the image of my application on computer my into a file. I used the JFileChooser to let the users choose their desired location for saving the file. The problem is unless user explicitly types in the file format, it saves the file with no extension. How can I have formats like jpg, png in the File Type drop down menu.

以及如何从文件类型下拉菜单中获取扩展名保存我的图像文件。

and, how can i get extension from the File Type drop menu for saving my image file.

 ImageIO.write(image,extension,file);


推荐答案

最后,我解决了我自己的问题: -

Finally, i solve my own problem :-

JFileChooser FC=new JFileChooser("C:/");
FC.addChoosableFileFilter(new jpgSaveFilter());
FC.addChoosableFileFilter(new jpegSaveFilter());
FC.addChoosableFileFilter(new PngSaveFilter());
FC.addChoosableFileFilter(new gifSaveFilter());
FC.addChoosableFileFilter(new BMPSaveFilter());
FC.addChoosableFileFilter(new wbmpSaveFilter()); 

int retrival=m_fileChooser_save.showSaveDialog(null);

if (retrival == m_fileChooser_save.APPROVE_OPTION) 
   {

        String ext="";

        String extension=m_fileChooser_save.getFileFilter().getDescription();

       if(extension.equals("*.jpg,*.JPG"))
      { 
          ext=".jpg";
      }
      if(extension.equals("*.png,*.PNG"))
      { 
          ext=".png";
      }
      if(Extension.equals("*.gif,*.GIF"))
      { 
          ext=".gif";
      }
      if(extension.equals("*.wbmp,*.WBMP"))
      { 
          ext=".wbmp";
      }
      if(Extension.equals("*.jpeg,*.JPEG"))
      { 
          EXT=".jpeg";
      }
      if(extension.equals("*.bmp,*.BMP"))
      { 
          ext=".bmp";
      }

示例过滤器:

 import java.io.*;
 import java.io.File;
 import java.util.*;
 import javax.swing.filechooser.FileFilter;   
 class jpgSaveFilter extends FileFilter
 { 
    public boolean accept(File f)
   {
        if (f.isDirectory())
          {
            return false;
          }

         String s = f.getName();

        return s.endsWith(".jpg")||s.endsWith(".JPG");
   }

   public String getDescription() 
  {
       return "*.jpg,*.JPG";
  }

}

这篇关于如何使用JFileChooser保存文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆