2014-07-01 56 views
0

我正在使用Document方法createPositionPositions添加到数组中。这些Positions根据用户插入/删除行而改变。跟踪文档位置更改

如何挂钩我的数组中的更改?我需要知道它的新价值和价值。

+1

@AndrewThompson因为我正在构建一个自定义的调试IDE,我需要知道是否设置了断点的行已经改变。 – LiquidBacon

回答

1

接口位置没有方法添加监听器来监视位置变化。所以你需要手动使用位置对象的包装。

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及其位置的包装,并在这些包装上注册您的事件监听器。