2011-09-23 86 views
3

我實際上在用JTextArea處理JScrollPane時沒有問題... 但是這裏...我有一個JPanel。我想使用Scroll。如何在JPanel上使用滾動? (Swing)

看看我在這裏的JPanel Image Preview。 我不知道如何在netbeans中做到這一點。我想我應該做一些自定義編碼。 所以,我試圖這樣做;

1)右鍵單擊jPanel2,自定義代碼。 2)使用此修改後的代碼;

初始化代碼:

jPanel2 = new javax.swing.JPanel(); 
scrb = new javax.swing.JScrollPane(jPanel2); 
// Code of sub-components - not shown here 

// Layout setup code - not shown here 
scrb.setPreferredSize(jPanel2.getPreferredSize()); 
jPanel1.add(jPanel2, "card2"); 

變量聲明代碼:

private javax.swing.JPanel jPanel2; 
private javax.swing.JScrollPane scrb; 

然後再重新運行我的工程.... 但是,...嘆息。 Scroll沒有進入正在運行的應用程序。

有什麼我忘了在這裏?

我試圖操縱jPanel2的大小,但因此不工作.... Scroll沒有出現。

回答

6

的問題是在這條線:

jPanel1.add(jPanel2, "card2"); 

取而代之的是這樣寫:

jPanel1.add(scrb, "card2"); 

你在做什麼是添加jPnael2到scrollpant但隨後而不是增加該滾動到JPANEL1您將jPanel2添加到jPanel1,以便scrollPane甚至不會出現在圖片中。

+0

但是,該代碼受NetBeans保護....如何解決它? 我意識到這一點,因爲我的jPanel1使用CardLayout ...嘆氣:( – gumuruh

+0

*「但是,該代碼受NetBeans保護....如何解決它?」*瞭解如何使用您的工具(而不是讓工具使用你)。 –

+0

hehehe ...好吧。謝謝@AndrewThompson – gumuruh

0

除了其他建議到滾動添加到面板上,我不知道這是否會因爲下面的代碼行的工作:

scrb.setPreferredSize(jPanel2.getPreferredSize()); 

滾動條只出現當添加到滾動窗格的組件的首選大小大於滾動窗格的大小時。所以如果你的佈局管理器尊重組件的首選大小,這個條件永遠不會是真的。

0

如果您使用的是NetBeans IDE,最好使用GUI設計器來創建滾動窗格。使用以下步驟來實現滾動窗格:

1. In Netbeans GUI editor, select all panels which requires scroll pane using CTRL+left click 
    2. Right click on the highlighted panels, select the option 'Enclose in' -> Scroll Pane. This will add a scroll pane for the selected panels. 
    3. If there are other elements than Panel(say JTree), select all the elements ->Enclose in ->Panel. Then enlose the new parent panel to scroll pane 
    4. Make sure that 'Auto Resizing' is turned on for the selected parent panel(Right click on panel -> Auto resizing -> Tick both Horizontal and vertical)