2011-09-28 23 views
0

我有一些物體orderProperty釉面列表排序列表更新時,源對象爲了改變性質

class Car 
{ 
    private int order; 

    // getter and setter implementation 
} 

然後,我創建EVENTLIST:

EventList<Car> cars=new BasicEventList<Car>() 
for (i=0;i<10;i++) {Car car=new Car(i); cars.add(car);} 

然後,我創建排序列表基於汽車使用它的TableModel

SortedList<Car> sortedCars=new SortedList<Car>(cars,carsComparator); 

這裏是比較器:

Comparator<Car> carsComparator implements Comparator<Car> 
{ 
      @Override 
      public int compare(Car o1, Car o2) { 
       return o1.getOrder() - o2.getOrder(); 
      } 
} 

在程序中有一些事件會改變car.order屬性。如何通知有關此更改的列表?

+0

我發現了一個醜陋但簡單的解決方案:在任何訂單屬性更改後調用Collections.sort(sortedCars,carsComparator) –

回答

0

問:如何通知有關訂單更改的列表?

可能的情況不一定是最好的情況。

該班車可以執行Observer design pattern。然後在每個製片人之後,可以通過更改值來通知聽衆。

在創建列表的代碼中,您可以將偵聽器添加到汽車中,以檢查訂單屬性更改並重新排列列表。

中的示例事件

public class PropertyChangeEvent extends EventObject { 

    private final String propertyName; 
    private final Object oldValue; 
    private final Object newValue; 

    public PropertyChange(String propertyName, Object oldValue, Object newValue) { 
    this.propertyName = propertyName; 
    this.oldValue = oldValue; 
    this.newValue = newValue; 
    } 

    public String getProperty() { 

    reutnr this.propertyName; 
} 

    //Rest of getters were omitted. 

} 

與聽者

public abstract interface PropertyChangeListener extends EventListener { 

    public abstract void propertyChange(PropertyChangeEvent event); 

} 

那麼你應該寫一個類,將支持該特性的改變,是應該有一個像addPropertyChangeListener(的PropertyChangeListener PCL)中的firePropertyChange(方法PropertyChangeEvent pce)。

當財產變更經理完成。只有你必須做的是。

public class Car { 

    private PropertyChangeManager manager = new PropertyChangeManager(Car.class); 


    /* The omitted code*/ 

    public void setOrder(int order) { 
     int oldValue = this.order; 
     this.order = order; 
     manager.firePropertyChange("order", oldValue, this.order); 
    } 

    public void addPropertyChangeListener(PropertyChangeListener pcl) { 
    this.manager.addPropertyChangeLIstener(pcl); 
    } 
} 

而在你使用該列表的類中。

private SortedList<Car> sortedCars=new SortedList<Car>(); 

    private PropertyChangeListener listReorder = new ProprtyChangeListener() { 

     @Override 
     public void propertyChange(PropertyChangeEvent event) { 

      if("order".equals(event.getProperty()) { 
       reoderCars(); 
      } 

     } 

    public boolean addCarToOrderList(Car car) { 
      /* Safety code omitted */ 

     boolean result = false; 

     if(sortedCars.contains(car) == false) { 
      result = sortedCars.add(car); 
     } 

     if(result) { 
      car.addPropertyChangeListener(listReorder); //We assume that this is safe 
     } 

     return result; 
    } 

    public void reoderCars() { 

    synchronized(this.sortedCar) { 
     //the code that will sort the list. 
    } 
    }