Search code examples
javaarraylistindexingjtextfielddocumentlistener

How to get index of an object with documentListener?


I have 2 lists displayed vertically in a JFrame. Lets say list A is an ArrayList<CustomTexField> and list B is an ArrayList<JLabel>.

I want to "update" the elements of list B that matches the same index of elements inside list A with the value from the CustomTextField.

I've tried adding document listener, but don't know how to calculate the index.

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

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

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

    }

I have also created a method inside CustomTexField class that saves the index when its created but don't know how to 'read' it from e.getDocument()

EDIT: UPDATED TITLE


Solution

  • If you're just trying to get the index of an item in an arraylist, you can just use the indexOf method.

    int indexOfItem = arrayList.indexOf(itemIWant)
    

    This is just how I interpreted your question but I would love clarification.

    EDIT: If you're trying to get the object attached to the DocumentListener, you can check out this question: how to find source component that generated a DocumentEvent

    Basically, if you have a DocumentListener for each CustomTextField, you can use the putProperty method described in the link to attach itself to it. From there, you can use getProperty(item) to find the item. You can do something similar with the index if you want but I believe that since you have an index field in your definition of CustomTextField, just attaching the CustomTextField with the DocumentListener will be enough.

    //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();
        }
    
    }