javabean的簡單實現



1.理解JavaBean的概念和特性。 

2.掌握編寫JavaBean的方法和注意事項。

3. 掌握JavaBean事件模型的實現。

1.構造監聽器類VetoableScoreListener

import java.beans.PropertyChangeEvent;

import java.beans.PropertyVetoException;

import java.beans.VetoableChangeListener;

 

public classVetoableScoreListener implementsVetoableChangeListener

{

   publicvoidVetoableChange(PropertyChangeEvent event)throwsPropertyVetoException

   {

    Object newValue=event.getNewValue();

    int Value=((Integer)newValue).intValue();

    if (Value<0||Value>100)

     {

       throw newPropertyVetoException("成績不符合要求",event);

     }

   }

@Override

public voidvetoableChange(PropertyChangeEvent evt)

     throws PropertyVetoException {

   // TODO Auto-generated method stub

  

}

}

2.構造限制類retoableScore

import java.beans.PropertyChangeEvent;

import java.beans.PropertyVetoException;

import java.beans.VetoableChangeListener;

import java.beans.VetoableChangeSupport;

 

public classretoableScoreextends Score

{

   privateVetoableChangeSupportsupport=newVetoableChangeSupport(this);

   privateintvalue;

  publicvoidaddVetoableChangeListener(VetoableChangeListenerlistener)

   {

    support.addVetoableChangeListener(listener);

   }

  publicvoidremoveVetoableChangeListener(VetoableChangeListenerlistener)

   {

     support.removeVetoableChangeListener(listener);

   }

   publicvoidsetValue(intvalue)

   {

     PropertyChangeEventevent=newPropertyChangeEvent(this,"value",newInteger(value),newInteger(value));

     try

     {

       

       support.fireVetoableChange(event);

       super.value=value;

     }

     catch (Exception e)

     {

       System.out.println(e.toString());

     }

   }

}

3.構造score類以及測試類

public classScore

{

  protectedintvalue;

 

  Score()

  {

   value=0;

  }

  publicScore(intvalue)

  {

   this.value=value;

  }

  publicintget()

  {

   return value;

  }

  publicvoidset(intvalue)

  {

    this.value=value;

  }

public voidaddVetoableChangeListener(VetoableScoreListener listener){

   // TODO Auto-generated method stub

  

}

public classTest{

   public static void main(String args[])

   {

     retoableScore score=newretoableScore();

     VetoableScoreListener listener=newVetoableScoreListener();

     try

     {

        

        

        score.setValue(10);

        PropertyChangeEvent event=newPropertyChangeEvent(score, "value", 10,10);

        listener.VetoableChange(event);

        System.out.println(score.get());

        

        score.setValue(-10);

        PropertyChangeEvent event1=newPropertyChangeEvent(score, "value", -10,-10);

        listener.VetoableChange(event1);

        System.out.println(score.get());

        

        

     }

     catch (Exception e)

     {

        System.out.println(e.toString());

     }

     

   }

 

 

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章