2016-09-09 84 views
1

我有一個帶有JPanel的JScrollPane。我在JPanel上也有很多不同的組件(例如Labels,JTextFields和JTextAreas)。這些組件以編程方式添加(在運行時,根據用戶請求)。 JPanel使用SpringLayout。程序在添加組件後計算JPanel的首選大小,因爲如果不進行計算,滾動功能將無法正常運行。添加組件和計算首選大小是我的prepareGui()方法的一部分。 組件上顯示的數據會定期刷新(在我的refreshData()方法中,由偵聽器調用)。數據刷新後滾動條移動

我的問題:刷新後,滾動條總是設置爲固定位置(我不知道爲什麼)。我想讓滾動條在刷新後保持舊位置。

我試圖找到一個地方,滾動條移動。我查了一些值在開始和refreshData()方法的末尾,但它們是相同的(他們沒有refreshData內改變()):

scrollPane.getVisibleRect().getX() 
scrollPane.getVisibleRect().getY() 
scrollPane.getVisibleRect().getWidth() 
scrollPane.getVisibleRect().getHeight() 
panel.getVisibleRect().getX() 
panel.getVisibleRect().getY() 
panel.getVisibleRect().getWidth() 
panel.getVisibleRect().getHeight() 
scrollPane.getHorizontalScrollBar().getX() 
scrollPane.getHorizontalScrollBar().getY() 
scrollPane.getHorizontalScrollBar().getWidth() 
scrollPane.getHorizontalScrollBar().getHeight() 
scrollPane.getHorizontalScrollBar().getValue() 
scrollPane.getVerticalScrollBar().getX() 
scrollPane.getVerticalScrollBar().getY() 
scrollPane.getVerticalScrollBar().getWidth() 
scrollPane.getVerticalScrollBar().getHeight() 
scrollPane.getVerticalScrollBar().getValue() 

佈局管理不斷變化的沒拿影響。

我注意到一件事(我不知道它是否有任何意義)。當我只設置首選大小時(在prepareGui())中,滾動條移動到最後。當我設置大小時,滾動條移動到奇怪的固定位置。

我該如何預防? 滾動條應保持當前位置。

回答

1

我終於在這裏找到了答案:https://stackoverflow.com/a/5230477/5694159(感謝Johan M)關於JTextArea而不是JPanel的主題。 當refreshData()在單獨的線程中調用時,它的效果很好。

我希望這個問題和答案能幫助別人。