2016-07-18 65 views
0

我正在嘗試創建一個簡單的Swing UI,它顯示文本區域的列表,全部在下面。 我想要一個滾動條,允許我在列表中垂直滾動。Java swing - 可滾動GridLayout中的項目不可見

但是,我似乎無法使網格中的條目可見並保持這種狀態。

似乎條目出現一小會兒然後再消失。我根本無法理解它。

這裏是我的代碼:

public class MyWindow extends JFrame { 
JPanel stretchPanel; 
JScrollPane scrollpane; 
JPanel centrePanel; 
JScrollBar scrollbar; 

public MyWindow(String title) { 
    super(title); 
    BorderLayout layout = new BorderLayout(); 
    setLayout(layout); 

    stretchPanel = new JPanel(); 
    scrollpane = new JScrollPane(); 
    stretchPanel.setLayout(new FlowLayout()); 
    centrePanel = new JPanel(); 
    centrePanel.setLayout(new GridLayout(0, 1)); 
    scrollbar = new JScrollBar(JScrollBar.VERTICAL); 
    scrollpane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 
    scrollpane.setVerticalScrollBar(scrollbar); 

    scrollpane.setViewportView(stretchPanel); 
    stretchPanel.add(centrePanel); 
    scrollpane.add(stretchPanel); 
    add(scrollpane, BorderLayout.CENTER); 
    fillGrid(); 
    setVisible(true); 
} 

public void fillGrid() { 
    centrePanel.removeAll(); 
    for (int i = 0; i < 20; i++) { 
     TextField entry = new TextField("Hello"); 
     centrePanel.add(entry); 
    } 
    scrollpane.setPreferredSize(new Dimension(800, 700)); 
    pack(); 
} 

public static void main(String[] args) { 
    new MyWindow("d"); 
} 

} 

任何幫助,不勝感激!

回答

2

您正在將您的JPanel添加到JScrollPane中,這是您永遠不應該做的事情。您需要使用JPanel設置視圖端口視圖,以便將其添加到JScrollPane的視口中,如JScrollPane教程和API所解釋的。所以不

scrollpane.add(stretchPanel); 

而是

scrollpane.setViewportView(stretchPanel); 

其他問題:

  • 爲什麼要創建自己的JScrollBar,而不是使用由JScrollPane的默認提供的?
  • 由於您顯示的是JTextField的網格,因此您可能應該創建並顯示JTable。
+0

謝謝,看來我同時調用了add和setviewportview。刪除添加電話解決了我的問題。我只是試圖讓滾動條顯示我以前掙扎過的滾動條。 –