2013-06-03 29 views
2

我試圖在運行時每次按下按鈕時將新面板插入另一個面板。我的問題是原來的面板用完了空間,我看不到我添加的新面板。如何在運行時將JPanel添加到具有垂直滾動窗格的另一個JPanel中?

我試過到目前爲止:

  • 對於沒有成功垂直滾動使用滾動窗格。
  • 使用flowlayout-沒有運氣。嘗試禁用水平滾動 - 不斷推新面板到右邊(因爲沒有滾動,無法進入)。
  • 嘗試使用borderlayout - 沒有運氣。

testpanel t = new testpanel(); 
t.setVisible(true); 
this.jPanel15.add(t); 
this.jPanel15.validate(); 
this.jPanel15.repaint(); 

此代碼假定對t面板插入jpanel15。 隨着flowlayout它推動t面板向下,就像我想要它,但沒有垂直滾動。

PS:我使用netbeans來創建我的GUI。

回答

0
  1. 使用JScrollPane代替(外)JPanel
  2. ,或者要向JPanel一個BorderLayout,放於JScrollPaneBorderLayout.CENTER作爲唯一的控制。作爲視圖,JScrollPane需要常規的JPanel

在任何情況下,你會再添加控件到JScrollPane。假設你JScrollPane變量是spn,你的控件添加爲Ctrl:

// Creation of the JScrollPane: Make the view a panel, having a BoxLayout manager for the Y-axis 
JPanel view = new JPanel(); 
view.setLayout(new BoxLayout(view, BoxLayout.Y_AXIS)); 
JScrollPane spn = new JScrollPane(view); 

// The component you wish to add to the JScrollPane 
Component ctrl = ...; 

// Set the alignment (there's also RIGHT_ALIGNMENT and CENTER_ALIGNMENT) 
ctrl.setAlignmentX(Component.LEFT_ALIGNMENT); 

// Adding the component to the JScrollPane 
JPanel pnl = (JPanel) spn.getViewport().getView(); 
pnl.add(ctrl); 
pnl.revalidate(); 
pnl.repaint(); 
spn.revalidate(); 
+0

注意,在案件1 /視圖JScrollPane也是一個JPanel。您將不得不爲自己設置添加控件的對齊方式,例如ctrl.setAlignmentX(Component.LEFT_ALIGNMENT);

+0

'JPanel pnl =(JPanel)spn.getViewport().getView();'返回null.it不返回面板。我將JScrollPane添加到我的主面板,並複製了上面的代碼的其餘部分,但得到空指針異常。 – user1864229

+0

您將不得不將JScrollPane創建爲JScrollPane spn = new JScrollPane(new JPanel())'。這就是我所說的將視圖設置爲JPanel(構造函數中的參數稱爲view的原因)。您可以將滾動窗格設置爲內容窗格,以防您的容器從RootPaneContainer派生(例如JFrame或JDialog)。 –

1

我的問題是原來的面板運行的空間,我不能看到新的面板我加入。嘗試使用scrollpane進行垂直滾動,但沒有成功。

FlowLayout水平添加組件,而不是垂直添加組件,因此您永遠不會看到垂直滾動條。相反,你可以嘗試Wrap Layout

基本的代碼來創建滾動窗格是:

JPanel main = new JPanel(new WrapLayout()); 
JScrollPane scrollPane = new JScrollPane(main); 
frame.add(scrollPane); 

然後,當你動態地添加組件到主面板,你會怎麼做:

main.add(...); 
main.revalidate(); 
main.repaint(); // sometimes needed 
相關問題