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);
}
}
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());
}
}
}