2010-01-25 120 views
13

我有下面的代碼:JScrollPane的和JList的自動滾動

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

它能夠自動向下滾動。但是,如果我嘗試回滾重新讀取消息,它會強制向下滾動。 我該如何解決這個問題?

回答

-1

我認爲你想要做的是當你添加東西到你的messageList,而不是調整時,它向下滾動。所以,你的代碼看起來是這樣的:

Adjustable sb = messageScrollList.getVerticalScrollBar() 
boolean onBottom = sb.getValue() == sb.getMaximum(); 
// 
// add your message to the JList. 
// 
if(onBottom) sb.setValue(sb.getMaximum()); 

否則,你將需要告訴我們,如果調整是通過模型變化引起,或由鼠標,並期待通過API文檔我不知道是否有一個方法很簡單。雖然你可以看到AdjustmentEvent.getAdjustmentType()在這些情況下是否返回不同的值,但如果這是真的,那麼你可以在匿名內部類中使用if語句。

你可以嘗試的另一件事是將一些布爾變量添加到列表中的某個地方。然後,在您的處理程序中,檢查是否設置了該變量。如果是這樣,你做調整(並取消設置變量)否則,你忽略它。這樣,每個項目只會向列表中添加一個向下滾動。

+0

調整類型在兩種情況下都是相同的。如果添加了一條消息,我試過這個向下滾動。但如果我這樣做,最後添加的消息不可見。它滾動不夠。我該如何解決這個問題? – dododedodonl 2010-01-25 13:55:59

+0

嗯......嗯,你可以做的一件事就是在你添加一些東西到列表中時,在某處設置一個布爾變量。然後,在您的處理程序中,檢查是否設置了該變量。如果是這樣,你做調整(並取消設置變量)否則,你忽略它。這樣,每個項目只會向列表中添加一個向下滾動。 – 2010-01-25 14:23:47

1
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()); 
1

我發現這真的有用: http://forums.sun.com/thread.jspa?threadID=623669(後由「inopia」)
它完美

正如他所說: 「這裏的問題是,它可以成爲一個有點難以找到在ListModel,JList和JScrollPane更新後觸發的事件。「

+0

鏈接已死亡。你能刷新它嗎? – 2011-10-15 00:16:43

0

要自動滾動我用一個很簡單的靜態變量和list.makeVisible(INT指數)

public class autoScrollExample 
    { 
    static int index=0; 
    private void someFunction() 
    /* 
    * 
    */ 
    list1.add("element1"); 
    list1.makeVisible(index++); 
    /* 
    * 
    */ 

    private void someOtherFunction() 
    /* 
    * 
    */ 
    list1.add("element2"); 
    list1.makeVisible(index++); 
    /* 
    * 
    */ 


    } 
1

@question詢問者的概念。請從

messageScrollList.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() { 
     public void adjustmentValueChanged(AdjustmentEvent e) { 
      e.getAdjustable().setValue(e.getAdjustable().getMaximum()); 
     } 
    }); 

改變你的代碼,以

messageScrollList.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() { 
     public void adjustmentValueChanged(AdjustmentEvent e) { 
      e.getAdjustable().setValue(e.getAdjustable().getValue()); 
     } 
    }); 

也就是說變化getMaximum()getValue()的要求,然後它工作。 getMaximum()將滾動條帶到最大值;而getValue()需要它在任何事件發生。

你能避免,如果你把一個行

messageScrollList.setViewportView(messageList); 

這就像add(component)爲的jList並得到其固有的行爲完全使用這段代碼。