2017-08-19 151 views
0

我是Java Swing的新手。有人能幫我弄清楚我做錯了什麼嗎?請在必要時糾正我。這段代碼的很大一部分是試錯。JScrollPane似乎沒有滾動

我有一個框架,其中包含一個JPanel。 JPanel使用「GridBag」佈局。代碼包括在圖片中看到的右側兒童JPanel周圍。出於某種原因,我似乎無法讓我的垂直滾動條正常工作。

這裏有感興趣的代碼:

/// GridBagConstraints 
GridBagConstraints gbc = new GridBagConstraints(); 

// parent jpanel for scrollpane 
scrollPanel = new JPanel(); 
scrollPanel.setLayout(new BorderLayout()); 
gbc.gridx = 1; 
gbc.gridy = 0; 
gbc.weightx = 1.0; 
gbc.weighty = 1.0; 
gbc.fill = GridBagConstraints.BOTH; 
add(scrollPanel, gbc); 

// content jpanel for scrollpane 
scrollPaneContent = new JPanel(); 
scrollPaneContent.setLayout(new GridLayout(0, 1, 0, 1)); 

// scrollPane 
scrollPane = new JScrollPane(); 
scrollPane.setBorder(BorderFactory.createEmptyBorder(0,30,0,0)); 
scrollPane.setViewportView(scrollPaneContent); 
scrollPanel.add(scrollPane, BorderLayout.PAGE_START); 

這裏是程序的樣子的時刻。 你可以看到的數字只是去關閉屏幕:

enter image description here

任何幫助,不勝感激!謝謝。

+0

爲了更快得到更好的幫助,請發佈[MCVE]或[簡短,獨立,正確的示例](http://www.sscce.org/)。 –

回答

1
scrollPanel.add(scrollPane, BorderLayout.PAGE_START); 

您正試圖將scrollPane添加到scrollPanel。這不是它的工作方式。

JScrollPane一個是一個容器,所以需要如此組成的面板添加到滾動窗格

JPanel panel = new JPanel(...); 
panel.add(....); 
panel.add(....); 
JScrollPane scrollPane = new JScrollPane(panel); 
frame.add(scrollPane); 

上面的代碼將所述面板添加到滾動窗格「視口」。

+0

我將scrollPane添加到scrollPanel,並使用scrollPaneContent作爲JScrollPane的視口,如下所示:scrollPane.setViewportView(scrollPaneContent);.這是不正確的?謝謝。 – gab64

+0

@ gab64,'這是不正確的嗎?' - 我已經告訴過你這是不正確的,並告訴你正確的方法。 – camickr

+0

我明白了。我現在正以正確的方式工作,謝謝。作爲替代,我發現它也適用於:setMinimumSize和setPreferredSize,但我試圖避免硬編碼的大小。再次感謝! – gab64