Search code examples
javaswinglistmodel

How exactly do I use the "fireContentsChanged" method in java.swing.AbstractListModel?


How exactly do I use the fireContentsChanged() method in java.swing.AbstractListModel? This method is called when some of the ListModel's elements have their "contents" changed.

  1. Does this only mean that the index's object has changed somehow?
  2. Or does it also include when the index's object has been replaced with a different object?
  3. Can you use this for added/removed indexes? For example, let's say I remove 10 random elements from anywhere in the list. What index0 and index1 do I give? What if I insert 10 elements in random places?

Solution

  • AbstractListModel is an abstract implementation of ListModel that provides concrete implementations of the ListDataListener methods, but it contains no specific data structure internally. Receipt of a corresponding ListDataEvent allows the listening JList to update itself in response to a change in the ListModel. DefaultListModel is a typical concrete subclass of AbstractListModel that manipulate a Vector internally. The source illustrates typical usage. In particular, fireContentsChanged() is "Sent when the contents of the list has changed in a way that's too complex to characterize with the previous methods," fireIntervalAdded() or fireIntervalRemoved(). Because Vector is a legacy of the original DefaultTableModel, you'll want to use a more flexible alternative; index0 and index1 refer to elements of your chosen data structure.

    What if I insert 10 elements in random places?

    Then index0 and index1 should "bracket the change."

    What does "bracket the change" mean?

    In this context, bracket is used as a verb meaning to enclose or include; index0 should include the lowest changed index, and index1 should include the highest changed index. The range may include intervening cells, even though they were not changed. Happily, like JTable, JList renders only visible cells, so the marginal cost is bounded; more here.