next up previous contents
Next: 実習環境について Up: Beans 作成サンプル Previous: NotVisible サンプル

BeanInfo サンプル

これまでの例は、beanのプロパティがIntrospectionで探されて、条件を満たした プロパティが BeanBoxのプロパティ・シートに表示されるというものでした。 beanの種類によっては、こうして得られる全てのプロパティを編集する必要が無いもの がありえます。 BeanBoxのサンプルの中では、OurButtonとExplicitButtonの関係が その例の一つになっていました。

このコントロールには、BeanInfoクラスを用います。 ここでは、BeanInfoを使って、プロパティの表示をコントロール出来ることを 学びます。

MyViewerサンプル

次のものは。fileNameという名前のプロパティに設定された文字列を、ファイル名と 解釈して、その内容をTextAreaに表示する簡単なbeanです。

==================================================================
import java.awt.*;
import java.io.*;

public class MyViewer extends TextArea  {
  String fileName="";

  public void setFileName(String s){
     fileName = s ;
     loadFile(s);
     setEditable(false);
     setVisible(true);
  }
  public String getFileName(){
     return fileName;
  }

  void loadFile(){
     if ( fileName.length() == 0 ) return ;
     try {
        BufferedReader in
             = new BufferedReader(new FileReader( fileName ));
        setText("");
        String line = "" ;
        String text = "" ;
        while( (line = in.readLine()) != null ){
           text += line + "\n" ;
        }
        setText(text);
     } catch (Exception ex){
        System.out.println("Exception : " + ex );
     }
  }
}
==================================================================

MyViewerBeanInfo

このクラスをbeanとしてBeanBoxにかけると、沢山のプロパティが表示されます。 今回は、この表示をfileNameプロパティだけにしてみようと思います。

まず、bean名+BeanInfoというクラスを同じディレクトリ内に作ります。 この例の場合でしたら、MyViewerBeanInfoというクラスを作る必要があります。 次がそのリストです。

==================================================================
import java.beans.*;

public class ViewerBeanInfo extends SimpleBeanInfo {
     private final static Class beanClass = Viewer.class;

     public PropertyDescriptor[] getPropertyDescriptors() {
        try {
            PropertyDescriptor fileName =
			new PropertyDescriptor("fileName", beanClass);
            fileName.setBound(true);

            PropertyDescriptor rv[] = { fileName };
            return rv;
        } catch (IntrospectionException e) {
            throw new Error(e.toString());
        }
    }

}
==================================================================

SimpleBeanInfoは、それ自身は何の情報も持っていませんが、それを拡大・継承する ことで、新しい情報を追加することが出来ます。この例では、BeanInfoからプロパティ 情報を取り出す getPropertyDescriptorsメソッドが置き換わっています。 BeanBoxは、対応するBeanInfoがある場合には、全てのプロパティを表示するのでは なく、このgetPropertyDescriptorsメソッドが返すプロパティのみを表示します。



maruyama@wakhok.ac.jp