2011-09-23 119 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)