我使用Document
方法createPosition将Positions
添加到数组中。这些Positions
的变化取决于用户插入/删除行。
如何钩住数组中的变化?我需要知道新值和原来的值
Interface Position没有方法添加侦听器来监视位置变化。因此,您需要手动使用位置对象的包装器。
public class PositionHolder {
private int oldPosition;
private Position position;
private PropertyChangeSupport propertySupport = new PropertyChangeSupport(this);
public PositionHolder(Position aPos) {
position = aPos;
oldPosition = aPos.getOffset();
}
public void addPropertyChangeListener(PropertyChangeListener aListener) {
propertySupport.addPropertyChangeListener(aListener);
}
// same for remove listener
public void verifyPosition() {
// no custom if statement required - event is fiered only when old != new
propertySupport.firePropertyChangeEvent("position", oldPosition, position.getOffset());
oldPosition = position.getOffset();
}
public Position getPosition() {
return position;
}
}
public class PositionUpdater implements DocumentListener {
private List<PositionHolder> holders;
public PositionUpdater(List<PositionHolder> someHolders) {
holders = someHolders;
}
public void insertUpdate(DocumentEvent e) {
for (PositionHolder h : holders) {
h.verifyPosition();
}
}
public void removeUpdate(DocumentEvent e) {
insertUpdate(e);
}
public void changeUpdate(DocumentEvent e) {
insertUpdate(e);
}
}
JTextComponent textComp = // your text component
List<PositionHolder> holderList = new ArrayList<>(); // your list of positions
textComp.getDocument().addDocumentListener(new PositionUpdater(holderList));
现在你会得到通知,当位置改变。您只需要为您的位置用包装器填充holderList
,并在这些包装器上注册您的事件侦听器。