Reputation: 552
I am relativly new to Java, and especially to swing. I develop with Netbeans 6.8.
I have a JList that uses a custom AbstractListModel. This AbstractListModel tracks changes to the data in a database, and calls fireIntervalAdded when a new element is to be added to the list. This works perfectly.
The problem I am having is that I would like the JList (or JScrollPane) to automaticly scroll to the new element in the list. I have read that I could use JList.ensureIndexIsVisible, but I do not know how to get the reference to the instance of the JList from its associated ListModel (since I am fireing the 'fireIntervalAdded' from within the ListModel).
To explain a bit, I have built a poller within the ListModel to poll new data from an SQL server. Since I consider the ListModel as the "data source" of the list, it made sence to put the data retreival (and polling in my case) logic inside this ListModel. The tutorials do not seem to cover this specific need for control scrolling from the Model itself (which sort-of makes sense since the ListModel could be used in multiple JList at once.....)
What can-I do to make the JList scroll to the last created element from within the ListModel code?
Also, I imagine that I could fix my problem if I could find an event in the JList that would be fired when a new element is added, but I have found none!
Thanks
-- EDIT --
Ok, base on MadProgrammer's response, here is what I built:
public class JListDataListener implements ListDataListener {
JList _listToControl = null;
public JListDataListener(JList listToControl) {
this._listToControl = listToControl;
this._listToControl.getModel().addListDataListener(this);
}
public void intervalAdded(final ListDataEvent e) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
_listToControl.ensureIndexIsVisible(e.getIndex1() + 1);
}
});
}
public void intervalRemoved(ListDataEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
}
public void contentsChanged(ListDataEvent e) {
//throw new UnsupportedOperationException("Not supported yet.");
}
}
Upvotes: 1
Views: 1003
Reputation: 347194
Personally, I wouldn't try & change the ui directly from a model like this. You are better of attaching another listener to the model with a reference to the list in question, this makes the solution reusable.
I might be tempted to extend jlist & use a specialised inner listener, but that comes down to your requirements
Upvotes: 2