2013-06-28 7 views
1

순환 속성 변경 수신기를 설정했습니다. 클래스 A의 객체가 2 개 있습니다. 한 객체가 다른 객체의 변경 사항을 수신하도록하고 그 반대의 경우도 마찬가지입니다.순환 속성 변경 청취자

import java.beans.PropertyChangeEvent; 
import java.beans.PropertyChangeListener; 
import java.beans.PropertyChangeSupport; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.List; 

public class CyclicPCLTest { 

    public static class A implements PropertyChangeListener{ 
     private PropertyChangeSupport propertyChangeSupport; 
     private String date; 

     public A(String date) { 
      this.date = date; 
      propertyChangeSupport=new PropertyChangeSupport(this); 
     } 

     public String getDate() { 
      return date; 
     } 

     public void setDate(String date) { 
      String oldDate=this.date; 
      this.date = date; 
      propertyChangeSupport.firePropertyChange(new PropertyChangeEvent(this, "date", oldDate, this.date)); 
     } 

     public void addPropertyChangeListener(PropertyChangeListener listener){ 
      propertyChangeSupport.addPropertyChangeListener(listener); 
     } 

     @Override 
     public void propertyChange(PropertyChangeEvent evt) { 
      setDate ((String) evt.getNewValue()); 
     } 
    } 


    public static void main(String[] args) { 
     List<A> as= Arrays.asList(new A[]{new A("01/02/2011"), new A("01/02/2011")}); 
     as.get(0).addPropertyChangeListener(as.get(1)); 
     as.get(1).addPropertyChangeListener(as.get(0)); 

     as.get(0).setDate("02/02/2011"); 
     System.out.println("date of the other A "+as.get(1).getDate()); 

     as.get(1).setDate("03/02/2011"); 
     System.out.println("date of the other A "+as.get(0).getDate()); 
    } 
} 

코드 작품이 출력입니다 : 여기에 코드는 그것을 어떻게하는지 궁금하고

date of the other A 02/02/2011 
date of the other A 03/02/2011 

? 그것은 나에게 stackoverflow 오류를 제공해서는 안 될까요? 첫 번째 A가 업데이트되면 두 번째 A에게 알리고 두 번째 A는 업데이트되고 첫 번째 A에 알립니다. 이것은 영원히 계속되어야합니다. 코드 (즉

propertyChangeSupport.firePropertyChange(new PropertyChangeEvent(this, "date", oldDate, this.date)); 

oldDatethis.date은 본질적으로 동일하게 도달 할 때 oldValue같지

newValue-2 재귀 실행하는 경우 firePropertyChange에만 이벤트가 발생합니다

+0

디버그 및 테스트를 수행 했습니까? – sanbhat

답변

1

그게 전부 때문에 가 oldDate.equals(this.date) == true)이고 이벤트를 수신자에게 전파하지 않습니다.

firePropertyChange의 설명서를 확인하십시오.

등록 된 리스너에 대해 기존 PropertyChangeEvent를 실행하십시오. 아니요 이벤트의 이전 값과 새 값이 이고 값이이고 이 아닌 경우 이벤트이 발생합니다.

+0

아 .. 어떻게 그랬어! 감사 – sethu