 /** PlanarImageLoader Class
   * @version 1.0  18 Dec 2000
   * @author Lawrence Rodrigues
   **/
package com.vistech.jai.imageio;
import java.io.*;
import java.beans.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.lang.reflect.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.util.*;
import com.vistech.events.*;
import com.vistech.util.*;
import com.vistech.jai.util.*;
import com.sun.image.codec.jpeg.*;

import java.awt.image.RenderedImage;
import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;
import com.sun.media.jai.codec.*;

 /** A bean that loads images from a local directory or a jar file using the JAI codec.
   * @version 1.0  18 Dec 2000
   * @author Lawrence Rodrigues
   **/
  public class PlanarImageLoader extends JPanel{
     public final static int LOCAL_DIR =0;
     public final static int JAR =1;
     public String curImageStr;
     public String[] fileList;
     public int curImageId;
     JLabel jarFileL;
     JTextField txtField, dirField, filterField, jarFileField;
    

     JList itemList;
     int numImages =1;
     String filterString = "jpeg,gif,JPEG,GIF,JPG,jpg,tif,png,ppm,bmp";
     String currentDir;
     int imageSelectMode = LOCAL_DIR;
     String jarFile, jarPath;
     public Vector imgLst = new Vector();
     PlanarImage loadedImage = null;
     public Hashtable imageTable = new Hashtable();

     int sortMode = JarUtil.BY_ALPHA;
     boolean multiSelect= true;
     JCheckBox multiselCb;

     transient PlanarImage imageset[];
     transient JComboBox sortSelect;
     transient ComboBoxModel sortSelModel;
     String[] sortModeList = {"By date", "By alphabetical"};
     int[] sortEnum = {JarUtil.BY_DATE, JarUtil.BY_ALPHA};
     JButton browseButton, loadButton; 

     Vector listSelListeners = new Vector();
     JRadioButton jar, loc;
     JPanel pan;
     protected PropertyChangeSupport pcNotifier; 
     protected VetoableChangeSupport vetoNotifier;

     public PlanarImageLoader() {
        pcNotifier= new PropertyChangeSupport(this);
        vetoNotifier = new VetoableChangeSupport(this);
        createUI();
     }
     /**
       * @param onOff the multi-select flag.
       */
     public  void setMultiSelect(boolean mode){
        if(mode == true){
           itemList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
           multiselCb.setSelected(true);
           multiSelect = true;
        } else {
           itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
           multiselCb.setSelected(false);
           multiSelect = false;
        }
     }

     /**
       * @return the multi-select flag.
       */
     public boolean getMultiSelect(){
        return multiSelect;
     }

     /**
       * @param mode the sort mode.
       */
     public  void setSortMode(int mode){
        sortMode = mode;
        if(currentDir != null){
           if(jarFile != null)
           fetchFileNames(currentDir+File.separator+jarFile);
        }
     }

     /** @return the sort mode.
       */
     public int getSortMode(){
        return sortMode;
     }

     public void setLoadButtonLabel(String label){
        loadButton.setText(label);
     }

     public String getLoadButtonLabel(){
        return loadButton.getText();
     }

     public void browse(){
        Frame fr = new Frame();
        FileDialog fd = new FileDialog(fr, "", FileDialog.LOAD);
        ExtensionFilter flFilter= new ExtensionFilter(".jar, .zip");
        fd.setFilenameFilter(flFilter);
        fd.show();
        String dir = fd.getDirectory();
        if(dir != null){
           currentDir = dir;
           dirField.setText(dir);
           fetchFileNames(dir);
        }
        String fl = fd.getFile();
        if(fl != null){
           switch (imageSelectMode){
             case JAR: 
               jarFile = fl;
               jarFileField.setText(jarFile);
               jarPath = new String(currentDir+File.separator+jarFile);
               fetchFileNames(jarPath);
               break;
            case LOCAL_DIR:
              fetchFileNames(dir);
              String filepath = new String(fl);
              PlanarImage img = loadImage(filepath);
              if(img != null) {
                //target.setImage(img);
                int num = itemList.getSelectedIndex();
                imageTable.put(Integer.toString(num), img);
                //fireImageLoadedEvent(img);
             }
          }
       }
    }


    private void createUI(){
        pan = new JPanel();
        int indice[];
        multiselCb = new JCheckBox("Multi select");
        multiselCb.setSelected(true);
        sortSelModel  = new SortSelModel();
        sortSelect = new JComboBox(sortSelModel);
        multiselCb.addItemListener(
             new ItemListener(){
               public void itemStateChanged(ItemEvent ie){
                  JCheckBox cb = (JCheckBox)ie.getSource();
                  multiSelect= cb.isSelected();
                  if(multiSelect == true){
                    itemList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
                  } else {
                    itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                  }
               }
             }

         );
      
        JPanel attrpan = new JPanel();
        JLabel sortlab = new JLabel("Sort",SwingConstants.RIGHT);
        attrpan.add(multiselCb);
        attrpan.add(sortlab);
        attrpan.add(sortSelect);
    
        attrpan.setBorder(BorderFactory.createTitledBorder("File list attributes"));
        
        JPanel dirP = new JPanel();
        JLabel dirL = new JLabel("Directory ", SwingConstants.RIGHT);
        dirField = new JTextField(15);
        
        JPanel jarFileP = new JPanel();
        jarFileL = new JLabel("Jar File", SwingConstants.RIGHT);
        jarFileField = new JTextField(15);
        jarFileP.add(jarFileL);
        jarFileP.add(jarFileField);
        jarFileL.setEnabled(false);
        jarFileField.setEnabled(false);
     
        JPanel filtP= new JPanel();
        JLabel filtL = new JLabel("Filter ", SwingConstants.RIGHT);

        filterField = new JTextField(15);
        filterField.setText(filterString);
        filtP.add(filtL);
        filtP.add(filterField);

        browseButton = new JButton("Launch File Dialog");
 
        loadButton = new JButton("Load");
        loadButton.setBackground(Color.gray);
        JLabel ldlab = new JLabel("Load from", SwingConstants.LEFT);
        ButtonGroup bg = new ButtonGroup();
        jar = new JRadioButton("Jar", false);
        loc = new JRadioButton("Local Dir", true);
        bg.add(loc);
        bg.add(jar);
  
        ListModel  imageListModel = new AbstractListModel(){
              public int getSize(){
                 if(fileList == null) return 0;
                 else return fileList.length;
              }
              public Object getElementAt(int index){
                 if(fileList == null) return null;
                 if((index <0) || (index>fileList.length)) return null;
                 return fileList[index];
              }
         };

         itemList = new JList(imageListModel);
         // itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
         itemList.setVisibleRowCount(6);
         itemList.setBackground(Color.white);
         itemList.setForeground(Color.black);
         itemList.setFixedCellWidth(150);
         itemList.setFixedCellHeight(15);
         JScrollPane scp= new JScrollPane(itemList);

         JPanel selpan = new JPanel();
         selpan.add(ldlab);
         selpan.add(loc);
         selpan.add(jar);

         GridBagLayout  gb = new GridBagLayout() ;
         GridBagConstraints c = new GridBagConstraints();
         pan.setLayout(gb);
                 
         c.gridx =0;  c.gridy =0;
         c.insets = new Insets(5,1, 1,1);
         gb.setConstraints(filtL, c);
         pan.add(filtL);
         c.gridx =1;  
         c.insets = new Insets(10,1, 1,1);
         gb.setConstraints(filterField, c);
         pan.add(filterField);
         c.insets = new Insets(1,1, 1,1);
         c.gridwidth = 1;
         c.gridx = 0;  c.gridy =1;
         gb.setConstraints(dirL, c);
         pan.add(dirL);
         c.gridx = 1;
         c.insets = new Insets(1,1, 1,1);
         gb.setConstraints(dirField, c);
         pan.add(dirField);
         c.gridx = 0;  c.gridy =2;
         gb.setConstraints(jarFileL, c);
         pan.add(jarFileL);
         c.gridx = 1;  c.gridy =2;
         gb.setConstraints(jarFileField, c);
         pan.add(jarFileField);
         c.fill = GridBagConstraints.BOTH;
         c.gridx =2; c.gridy =0;
         c.gridwidth = 1;
         c.gridheight = 4;
         c.gridwidth = GridBagConstraints.REMAINDER;
         c.insets = new Insets(10,1, 1,1);
         scp= new JScrollPane(itemList);
         gb.setConstraints(scp, c);
         pan.add(scp);
         c.fill = GridBagConstraints.HORIZONTAL;
         c.gridheight = 1;
         c.gridwidth = 1;
         c.gridx =1;
         c.gridy =3;
         c.insets = new Insets(1,1, 1,1);
         gb.setConstraints(browseButton,c);
         pan.add(browseButton);
         c.gridx =1;
         c.gridy =4;
         c.gridwidth =2;
         gb.setConstraints(attrpan, c);
         pan.add(attrpan);
         c.gridx =1;
         c.gridy =5;
         gb.setConstraints(loadButton, c);
         pan.add(loadButton); 

         
         gb = new GridBagLayout() ;
         c = new GridBagConstraints();
         setLayout(gb);
         c.fill = GridBagConstraints.BOTH;
         c.insets = new Insets(10,1, 1,1);
         c.gridwidth = GridBagConstraints.REMAINDER;
         gb.setConstraints(selpan, c);
         add(selpan);
         c.insets = new Insets(1,1, 1,1);
         c.gridwidth = GridBagConstraints.REMAINDER;
         gb.setConstraints(pan, c);
         add(pan);
         setBorder(BorderFactory.createTitledBorder(new EtchedBorder(),"Image Loader"));
         addEventHandlers();
    }

    private void addEventHandlers() {
        browseButton.addActionListener(
            new ActionListener(){
               public void actionPerformed(ActionEvent e){
                  browse();
               }
            }
         );
        filterField.addActionListener(
            new ActionListener(){
               public void actionPerformed(ActionEvent e){
                  filterString = ((JTextField)(e.getSource())).getText();
                  if(filterString == null) return;
                  if((imageSelectMode == LOCAL_DIR) && (currentDir != null)) 
                      fetchFileNames(currentDir);
                  if((imageSelectMode == JAR) && (currentDir != null) && (jarFile != null)) 
                      fetchFileNames(jarFile);
               }
            }
         );
         dirField.addActionListener(
            new ActionListener(){
               public void actionPerformed(ActionEvent e){
                  String curDir = ((JTextField)(e.getSource())).getText();
                  if(curDir != null){
                     currentDir = curDir;
                     fetchFileNames(curDir);
                  }
               }
            }
        );

       jarFileField.addActionListener(
            new ActionListener(){
               public void actionPerformed(ActionEvent e){
                  String fl = ((JTextField)(e.getSource())).getText();
                  if(fl == null) return;
                  jarFile = fl;
                  if(dirField == null) return;
                  else  currentDir = dirField.getText();
                  if(currentDir == null){
                     //Fetch from current directory.
                     fetchFileNames(fl);
                  } else {
                     //Absolute path
                     jarPath = new String(currentDir+ File.separator+fl);
                     fetchFileNames(jarPath);
                  }
               }
            }
         );
        loadButton.addActionListener(
              new ActionListener(){
               public void actionPerformed(ActionEvent a){
                  if((itemList == null)|| (fileList == null)) return;
                  if(multiSelect){
                     int[] ind = itemList.getSelectedIndices();
                     if(ind == null) return;
                     String list[]  = new String[ind.length];
                     for(int i=0; i<ind.length;i++){
                         list[i] = fileList[ind[i]];
                     }
                     try {
                        File dir = new File(currentDir);
                        ListSelectEvent ls = new ListSelectEvent(
                                         PlanarImageLoader.this,
                                         a.getActionCommand(),
                                         dir,
                                         list);
                        fireListSelectEvent(ls);
                     } catch(Exception e) {};
                     load();
                  }
                  else {
                    int ind = itemList.getSelectedIndex();
                    String str = fileList[ind];
                    if((str == null) || (currentDir == null)) return;
                    PlanarImage img= loadImage(str);
                    if(img != null){
                       imageTable.put(Integer.toString(ind), img);
                       fireImageLoadedEvent(img);
                    }
                  }
              }
            }
        );

         MouseListener mouseListener = new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
              if (e.getClickCount() == 2) {
                  //System.out.println("Double clicked on Item " );
                  if((itemList == null)|| (fileList == null)) return;
                  int ind = itemList.getSelectedIndex();
                  String str = fileList[ind];
                  if((str == null) || (currentDir == null)) return;
                  PlanarImage img= loadImage(str);
                  if(img != null){
                     imageTable.put(Integer.toString(ind), img);
                     fireImageLoadedEvent(img);
                  }
              }
          }
        };

       itemList.addMouseListener(mouseListener);
       itemList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

       loc.addItemListener(
           new ItemListener(){
              public void itemStateChanged(ItemEvent e){
                 if(((JRadioButton)e.getSource()).isSelected()){
                      imageSelectMode = LOCAL_DIR;
                      if(jarFileField == null) return;
                      jarFileField.setEnabled(false);
                      jarFileL.setEnabled(false);
                      jarFileField.setEditable(false);
                 }
              }
           }
        );
 
        jar.addItemListener(
           new ItemListener(){
              public void itemStateChanged(ItemEvent e){
                 if(((JRadioButton)e.getSource()).isSelected()){
                      imageSelectMode = JAR;
                      if(jarFileField == null) return;
                      jarFileField.setEnabled(true);
                      jarFileL.setEnabled(true);
                      jarFileField.setEditable(true);
                     //loadJarImageFiles();
                 }
              }
           }
        );
    }

    protected void load() {
        if(itemList == null) return;
        int indice[];
        if(itemList.getSelectionMode() == ListSelectionModel.SINGLE_SELECTION) {
          indice = new int[]  {itemList.getSelectedIndex()};
        } else indice = itemList.getSelectedIndices();

        if(indice == null) return;

        String list[]  = new String[indice.length];
        imageset = new PlanarImage[indice.length];

        for(int i=0; i<indice.length;i++){
            list[i] = fileList[indice[i]];
            imageset[i] = loadImage(list[i]);
        }
        fireImageLoadedEvent(imageset);
   }
  
  /**  Fetches the image file names from the current path and
      *  adds them to the imageList.
      */
    protected void loadLocalImageFiles(File fl){
       jarFileField.setEnabled(true);
       jarFileL.setEnabled(true);
       jarFileField.setEditable(true);
       if(!fl.exists()){
           //target.displayStatusMessage("Customizer Message",
           //                     fl+ " does not exist, enter again ");
       }
       fileList = null;
       fileList = readLocalImageFileList(fl);
       if(fileList != null) itemList.setSelectedIndex(0);
       //setImageList(fileList);
    }

    /**
      *  Reads image file names from a local directory.
      *  @param dir the directory.
      */
    public String[] readLocalImageFileList(File dir){
       ExtensionFilter fFilter;// =  new ExtensionFilter("jpeg,gif,JPEG,GIF JPG,jpg");
       if(filterString != null)
          fFilter =  new ExtensionFilter(filterString);
       else fFilter =  new ExtensionFilter("jpeg,gif,JPEG,GIF JPG,jpg");

       fileList = dir.list(fFilter);
       if(fileList == null){
          System.out.println("null list");
          return null;
       }
       itemList.setSelectedIndex(0);

       numImages = fileList.length;
       return fileList;
    }

    /**  Fetches the image file names from the JAR and
      *  adds them to the fileList.
      */

    protected void loadJarImageFiles(File dir){
       jarFileField.setEnabled(true);
       jarFileL.setEnabled(true);
       jarFileField.setEditable(true);
       fileList = readJarImageFileList(dir);
       if(fileList != null) itemList.setSelectedIndex(0);

       //if(fileList != null) setImageList(fileList);
    }
    /**
      *  Reads image file names from a local directory.
      *  @param dir the directory.
      */
    public String[] readJarImageFileList(File jarfile){
       ExtensionFilter fFilter;// =  new ExtensionFilter("jpeg,gif,JPEG,GIF,JPG,jpg");
       if(filterString != null)
          fFilter =  new ExtensionFilter(filterString);
       else fFilter =  new ExtensionFilter("jpeg,gif,JPEG,GIF JPG,jpg,bmp, ppm, tiff, tif");
       String filter[] = {"jpeg","gif","JPEG","GIF", "JPG","jpg", "tif", "bmp", "ppm", "png"};
       fileList = JarUtil.listJarFiles(jarfile,filter,sortMode);

       if(fileList == null){
          System.out.println("null list");
          return null;
       }
       itemList.setSelectedIndex(0);
       numImages = fileList.length;
       return fileList;
    }


    public void setLoadMode(int mode){
       imageSelectMode = mode;
    }

    public int getLoadMode(){
        return imageSelectMode;
     }

    public void setLoadedImage(PlanarImage img){
       pcNotifier.firePropertyChange("loadeImage",
                                      this.loadedImage,
                                      img);
       loadedImage = img;
    }

    public PlanarImage getLoadedImage(){
       return loadedImage;
    }

    public PlanarImage getImage(int num){
      if(num <0 || num >= numImages){
         System.out.println(" Image does not exist " + num + " num Ima "+numImages);
         return null;
      }
      PlanarImage img = (PlanarImage)imageTable.get(Integer.toString(num));

      if(img == null){
         img = loadImage(fileList[num]);
         System.out.println("loading images ");
         if(img == null){
               System.out.println("can't load");
               return null;
          } else return img;
      } else{
          //System.out.println("load stat "+img.loadStatus);
          return img;
      }
    }

    public static PlanarImage readAsPlanarImage(String filename) {
        return JAI.create("fileload", filename);
    }
    public void addListSelectListener(ListSelectListener il){
        listSelListeners.addElement(il);
     }

     public void removeListSelectListener(ListSelectListener il){
        if(!(listSelListeners.isEmpty())) listSelListeners.removeElement(il);
     }

     /**
        * Fires list-select events to the registered listeners.
        * @param lse the ListSelectEvent.
        */
     protected void fireListSelectEvent(ListSelectEvent lse){
        if(listSelListeners.isEmpty()) return;
        Vector lstn = new Vector();
        synchronized(this){
          lstn = (Vector)listSelListeners.clone();
        }
        for(Enumeration e=lstn.elements();e.hasMoreElements();){
          ((ListSelectListener)(e.nextElement())).load(lse);
        }
     }

     public void addPlanarImageLoadedListener(PlanarImageLoadedListener il){
        imgLst.addElement(il);

     }
     public void removePlanarImageLoadedListener(PlanarImageLoadedListener il){
        if(!(imgLst.isEmpty())) imgLst.removeElement(il);
     }

   protected void fireImageLoadedEvent(PlanarImage img) {
       for(Enumeration e= imgLst.elements(); e.hasMoreElements();){
          PlanarImageLoadedEvent ie = new PlanarImageLoadedEvent(this, img);
          PlanarImageLoadedListener il = (PlanarImageLoadedListener)(e.nextElement());
          il.imageLoaded(ie);
       }  
       setLoadedImage(img);
   }

   protected void fireImageLoadedEvent(PlanarImage[] img) {
       if(img == null) return;
       for(Enumeration e= imgLst.elements(); e.hasMoreElements();){
          PlanarImageLoadedEvent ie = new PlanarImageLoadedEvent(this, img);
          PlanarImageLoadedListener il = (PlanarImageLoadedListener)(e.nextElement());
          il.imageLoaded(ie);
       }  
       setLoadedImage(img[0]);
   }

    /**
      * Reads the file names from the directory specified by the input.
      * @param filename the  directory name.
      */
    void fetchFileNames(String filename){
       if(filename==null) return;
       File fl = new File(filename);
       if(!fl.exists()) return;
       fetchFileNames(fl);
    }

    /**
      * Reads the file names from the directory specified by the input.
      * @param fl the  directory name.
      */
    void fetchFileNames(File fl){
      if(fl==null) return;
      String[] filter =null;
       if(filterString != null) {
          StringTokenizer st = new StringTokenizer(filterString, ",");
          int num= st.countTokens();
          filter = new String[num];
          for(int i=0;i<num;i++){
              filter[i] = (String)st.nextToken();
          }
       }
       if(imageSelectMode == LOCAL_DIR)  fileList = readLocalImageFileList(fl);
       else fileList = JarUtil.listJarFiles(fl, filter, sortMode);
       if(fileList == null){
           System.out.println(fl+ " is not a jar file or has no files ");
           return;
       }
       itemList.setSelectedIndex(0);
       itemList.revalidate();
       itemList.repaint();
    }

    public PlanarImage loadImage(String imagename) {
       PlanarImage img=null;
       if(imageSelectMode == LOCAL_DIR) {
          img = readAsPlanarImage(currentDir+ File.separator+imagename);
       }
       if(imageSelectMode == JAR) {
          if(jarPath == null) return null;
          img = JAIImageUtil.readJAIImage(jarPath, imagename);
       }
       return img;
    }

    class SortSelModel implements ComboBoxModel{
       transient int selIndex =0;
            public void addListDataListener(ListDataListener l){

             }
             public void removeListDataListener(ListDataListener l){

             }

             public int getSize(){
                return sortModeList.length;
             }

             public Object getElementAt(int index){
                return sortModeList[index];
             }

             public Object getSelectedItem(){
                if(sortModeList != null){
                   return sortModeList[selIndex];
                }
                return null;
             }

             public void setSelectedItem(Object item){
                for(int i=0;i<sortModeList.length;i++){
                    if(sortModeList[i] == item){
                       selIndex =i;
                       setSortMode(sortEnum[i]);
                       break;
                    }

                }
            }

    }

    public void save() {
       Rectangle rect = this.getBounds();
       int wid = rect.width;
       int ht = rect.height;
       if(wid <=1 ) wid = 400;
       if(ht <= 1 ) ht =300;
       System.out.println("save2");

       BufferedImage bi = new BufferedImage(wid, ht, 
                                            BufferedImage.TYPE_INT_RGB);
       Graphics2D g2d = bi.createGraphics();
       Image im = this.createImage(wid,ht);
       Graphics gx = im.getGraphics();
       JPanel pan1 = new JPanel();
       SwingUtilities.paintComponent(g2d,this,pan1, 0,0,wid,ht); 
       //browseButton.paint(gx);
       //g2d.drawImage(im,0,0,wid, ht,this);
       System.out.println("save1");
       save(bi);
    }

    public String launchFileDialog(){
        Frame fr = new Frame();
        FileDialog fd = new FileDialog(fr,"", FileDialog.SAVE);
        fd.show();
        String dir = fd.getDirectory();
        String file = fd.getFile();
        if((dir == null) || (file == null)) return null;
        String path = dir+file;
        int lastindex = path.lastIndexOf(".");
        if(lastindex <0) path += ".jpg";
        else {
          String sb = path.substring(lastindex);
          if(sb.equals(".jpg") || sb.equals(".jpeg")) return path;
          else {
            System.out.println(path + " enter extension .jpg or .jpeg");
          }
        }
        return path;
    }
    public void save(BufferedImage bi) {
       try {
         String filename = launchFileDialog();
         if(filename == null) return;
         ByteArrayOutputStream boutstream = new ByteArrayOutputStream();
         JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(boutstream);
         enc.encode(bi);
         FileOutputStream fimage = new FileOutputStream(new File(filename));
         boutstream.writeTo(fimage);  
         fimage.close();
         } catch (Exception e) {
         System.out.println(e);
       }
    }

    class  ExtensionFilter implements FilenameFilter{
      private String extString;
      public ExtensionFilter(String ext){
         extString = ext;
      }
      public boolean accept(File dir, String name){
	       StringTokenizer st = new StringTokenizer(extString, ",");
         while(st.hasMoreTokens()){
               String str = st.nextToken();
               String tok = str.trim();
               if(name.endsWith(tok)){
                  return true;
              }
          }
         return false;
      }
   }
    public static void  main(String[] args){
        PlanarImageLoader il = new PlanarImageLoader();
        JFrame fr = new JFrame();
        fr.addWindowListener(
            new WindowAdapter(){
               public void windowClosing(WindowEvent e){
                  System.exit(0);
               }
             }
        );

        fr.setTitle("Image Loader Bean");
        fr.getContentPane().add(il);
        fr.pack();
        Dimension d = il.getPreferredSize();
        fr.setSize(d.width+30, d.height+50);
        il.paintComponent(il.getGraphics());
        fr.show();
    }
  }