Glazed Lists当源对象顺序属性更改时,SortedList更新

时间:2011-09-28 08:11:13

标签: java collections glazedlists

我有一些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);}

然后我基于汽车创建SortedList以将其用于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属性。如何通知列表有关此更改?

1 个答案:

答案 0 :(得分:0)

问:如何通知列表订单更改?

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

班车可以实施Observer design pattern。然后在每个setter之后,您可以通过值更改通知侦听器。

在您创建列表的代码中,您可以将监听器添加到car,检查订单属性更改并重新排序列表。

示例事件

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.
     }
  }