I've got the next code:
listModel = new DefaultListModel();
listModel.addElement(dateFormat.format(new Date()) + ": Msg1");
messageList = new JList(listModel);
messageList.setLayoutOrientation(JList.VERTICAL);
messageScrollList = new JScrollPane(messageList);
messageScrollList.setPreferredSize(new Dimension(500, 200));
messageScrollList.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
e.getAdjustable().setValue(e.getAdjustable().getMaximum());
}
});
It auto scrolls down. But, if I try to scroll back up to re-read a message, it forces a scroll down. How can I fix this?
When adding a new message, invoke scrollRectToVisible()
on the JList
using a Rectangle
having the same dimensions as your message pane's preferred size. Given a vertical orientation, it may be convenient to make the preferred size of the JScrollPane
's JViewport
an integral multiple of the message pane's height. See also: How to Use Scroll Panes.
Addendum: This compelling discussion of Text Area Scrolling may be helpful, too.
this.list = blah blah...
this.list.setSelectedValue(whatever);
final JScrollPane sp = new JScrollPane(this.list); // needs to be after the parent is the sp
this.list.ensureIndexIsVisible(this.list.getSelectedIndex());
I found this really useful:
http://forums.sun.com/thread.jspa?threadID=623669 (post by 'inopia')
It works perfectly
As he says: "The problem here is that it can become a bit difficult to find an event that fires after both the ListModel, JList and JScrollPane have been updated."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With