Topic: 为什么运行结果会是这样? |
Print this page |
1.为什么运行结果会是这样? | Copy to clipboard |
Posted by: zhjdenis Posted on: 2007-10-03 20:38 使用限制属性,运行正常,但是为什么第二次由于属性被拒绝后连续打印了两个 “property: weightwill be changed”? 运行结果如下 property: weightwill be changed bean's value: weight: 20 second change: property: weightwill be changed property: weightwill be changed property: weight is veto bean's value: weight: 20 //以下是代码 package 限制属性; import java.beans.*; public class Mybean { private int weight; private transient VetoableChangeSupport veto=new VetoableChangeSupport(this); public int getweight() { return weight; } public void setweight(int weight) throws java.beans.PropertyVetoException { int oldweight=this.weight; veto.fireVetoableChange("weight",new Integer(oldweight),new Integer(weight)); this.weight=weight; } public String tostring() { String s="bean's value: "; s=s+"weight: "+weight; return s; } public synchronized void add(VetoableChangeListener x) { veto.addVetoableChangeListener(x); } } //以下是主测试程序代码 package 限制属性; import java.beans.*; public class Propertydemo { public static void main(String[] args) { // TODO Auto-generated method stub Mybean bean1=new Mybean(); bean1.add(new Myvetochangelistener()); System.out.println(bean1.tostring()); System.out.println("first change: "); try { bean1.setweight(20); } catch(PropertyVetoException ex) { System.out.println(ex.getMessage()); } System.out.println(bean1.tostring()); System.out.println("second change: "); try { bean1.setweight(150); } catch(PropertyVetoException ex1) { System.out.println(ex1.getMessage()); } System.out.println(bean1.tostring()); } } //以下是否决监听器的代码 package 限制属性; import java.beans.PropertyChangeEvent; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; public class Myvetochangelistener implements VetoableChangeListener { public void vetoableChange(PropertyChangeEvent y)throws PropertyVetoException { System.out.println("property: "+y.getPropertyName()+" will be changed"); if(((Integer)y.getNewValue()).intValue()>100) { throw new PropertyVetoException("property: "+y.getPropertyName()+" is veto",y); } } } |
Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1 客服电话 18559299278 客服信箱 714923@qq.com 客服QQ 714923 |