Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JScrollPane and JList auto scroll

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?

like image 392
dododedodonl Avatar asked Jan 25 '10 13:01

dododedodonl


3 Answers

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.

like image 157
trashgod Avatar answered Nov 11 '22 14:11

trashgod


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());
like image 39
Gene De Lisa Avatar answered Nov 11 '22 14:11

Gene De Lisa


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."

like image 1
mohsenof Avatar answered Nov 11 '22 13:11

mohsenof