如何使用 documentListener 获取 object 的索引?

How to get index of an object with documentListener?

我在 JFrame 中垂直显示了 2 个列表。假设列表 A 是 ArrayList<CustomTexField>,列表 B 是 ArrayList<JLabel>.

我想要 "update" 列表 B 的元素与列表 A 中元素的相同索引与 CustomTextField.

中的值相匹配

我试过添加文档监听器,但不知道如何计算索引。

@Override
    public void insertUpdate(DocumentEvent e) {
        try {

            listB().get(INDEX).setText(e.getDocument().getText(0, e.getDocument().getLength()) + "");

        } catch (BadLocationException e1) {
            e1.printStackTrace();
        }

    }

我还在 CustomTexField class 中创建了一个方法,它在创建索引时保存索引,但不知道如何 'read' 从 e.getDocument()

编辑:更新标题

如果您只是想获取数组列表中某项的索引,您可以使用 indexOf 方法。

int indexOfItem = arrayList.indexOf(itemIWant)

这就是我对你的问题的解释,但我希望得到澄清。

编辑:如果您试图将对象附加到 DocumentListener,您可以查看这个问题:how to find source component that generated a DocumentEvent

基本上,如果每个 CustomTextField 都有一个 DocumentListener,则可以使用 link 中描述的 putProperty 方法将自身附加到它。从那里,您可以使用 getProperty(item) 来查找该项目。如果需要,您可以对索引执行类似的操作,但我相信,由于您在 CustomTextField 的定义中有一个索引字段,因此只需将 CustomTextField 与 DocumentListener 连接就足够了。

//sometime on initalization of the lists
for(CustomTextField field: listA):
    field.getDocument().putProperty("owner", field);

...

@Override
public void insertUpdate(DocumentEvent e) {
    try {
        CustomTextField field = e.getDocument().getProperty("owner");
        int index = field.getIndex(); //assuming you have a getter method
        listB().get(index).setText(listA.get(index).getText());

    } catch (BadLocationException e1) {
        e1.printStackTrace();
    }

}

我会将所有 CustomTextField 存储在 Map<String, Integer> 中,其中键是 CustomTextField 的名称,值是唯一标识符。然后我会将你所有的 Label 放在另一个 Map<Integer, Label> 中,其中键是一个唯一标识符,对应于匹配 CustomTextField.

的唯一标识符

现在在您的 insertUpdate() 中您知道哪个 CustomTextField 正在更新,因此获取它的唯一标识符,例如:

int id = ctfMap.get(customTextField.getName());

使用此 ID 并像这样获取标签:

JLabel label = lblMap.get(id);

设置标签的文本:

label.setText = customTextField.getText();

我找到了答案 here。我还在 CustomTextFields 中添加了 focusListener,因此当重写 focusGained 方法时,我可以获得调用事件的对象并将其转换为我的自定义 class.

private class ListenForDoc implements DocumentListener, FocusListener{
    int index;
    @Override
    public void insertUpdate(DocumentEvent e) {
        try {

            listB().get(index).setText(e.getDocument().getText(0, e.getDocument().getLength()));


        } catch (BadLocationException e1) {
            e1.printStackTrace();
        }

    }

    @Override
    public void removeUpdate(DocumentEvent e) {
        //TO DO

    }

    @Override
    public void changedUpdate(DocumentEvent e) {}


    @Override
    public void focusGained(FocusEvent e) {
        Object o = e.getSource();
        if(o instanceof CustomTextField) {
            index = ((CustomTextField)o).getIndex();    
        }
        else{
        //HandleError
        }
    }

    @Override
    public void focusLost(FocusEvent e) {
        // TODO Auto-generated method stub      
    }

}