views:

670

answers:

2

Hi,

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);
+1  A: 

Use JFileChoose.SetFileFilter example: http://www.java2s.com/Code/JavaAPI/javax.swing/JFileChoosersetFileFilterFileFilterfilter.htm

Pierre
ok..setFileFilter will show the Extension in File Type drop down Menu.but how to retrieve or use selected Extension form this File Type Drop Menu..
Lokesh Kumar
Once you have the selected file, it should be as easy as String ext = file.getName().substring(file.getName().lastIndexOf("."));
gregcase
A: 

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";
      }

Example Filter:

 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";
  }

}
Lokesh Kumar