2016-10-26 66 views
0

我在JScrollPane中有一個面板,並且隨着從服務接收到數據,我動態地使用組件填充面板。該面板使用GridBagLayout(但應該是不相關的)。對於服務返回的每條記錄,我都會動態創建幾個組件並將它們附加到面板的底部。一切工作正常,但問題是,獲取每個記錄創建的JTextArea迫使主JScrollPane中向下滾動並顯示最後添加的JTextArea,如下所示:JTextArea強制父JScrollPane向下滾動

scroll pane forced down

我試圖禁用一切我可以想到愚蠢的JTextArea,但仍然沒有幫助

JTextArea descriptionArea = new JTextArea(project.getDescription().replace("<br>", "\n")); 
descriptionArea.setEditable(false); 
descriptionArea.setFont(thumbnailLabel.getFont()); 
descriptionArea.setLineWrap(true); 
descriptionArea.setWrapStyleWord(true);  
descriptionArea.setFocusable(false); 
descriptionArea.setRequestFocusEnabled(false);  
DefaultCaret caret = (DefaultCaret) descriptionArea.getCaret(); 
caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE); 

如何防止它移動滾動條?我嘗試用JLabel替換JTextArea,並且工作正常,但是我無法讓JLabel將文字換成文字。任何想法將不勝感激。

回答

2

你可以這樣做:

Point p = srcollPane.getViewport().getViewPostition(); 
// add the components to the panel in the viewport of the scrollpane 
scrollpane.getViewport().setViewPosition(p); 

現在你添加的組件之前滾動面板應恢復到原來的位置。

+0

謝謝。我之前已經嘗試過這個解決方案,但沒有奏效。我只是設法在執行包裝在SwingUtilities.invokeLater()調用中的setViewPosition時使其工作。 –