简体   繁体   English

如何使用嵌套的JPanel使JScrollPane正常工作?

[英]How do I make JScrollPane work properly with nested JPanels?

I'm building a Swing application in Java using NetBeans and I have a problem with layout. 我正在使用NetBeans在Java中构建Swing应用程序,我遇到布局问题。 My main frame contains a JScrollPane which contains a JPanel called contentPanel which in turn contains a JPanel called listPanel . 我的主框架包含一个JScrollPane ,它包含一个名为contentPanelJPanel ,后者又包含一个名为listPanelJPanel The listPanel is empty when the program starts, but when the user interacts with the program an unpredictable number of smaller JPanel s are added to it. 程序启动时listPanel为空,但是当用户与程序交互时,会向其添加不可预测数量的较小JPanel I've used the NetBeans GUI-builder to snap the top edge of listPanel to the top of contentPanel , and the same with the bottom edges. 我已经使用NetBeans GUI构建器将listPanel的上边缘listPanelcontentPanel的顶部,并将底边边缘相同。

The problem I have is that when more components are added to listPanel the vertical scrollbar doesen't appear on my scrollpane. 我遇到的问题是,当更多组件添加到listPanel ,垂直滚动条不会出现在我的滚动窗格上。 The verticalScrollBarPolicy of my scrollpane is set to AS_NEEDED and its viewportView is set to contentPanel . 我的滚动窗格的verticalScrollBarPolicy设置为AS_NEEDED ,其viewportView设置为contentPanel What I think I need to do is to make contentPanel grow when more items are added to listPanel . 我认为我需要做的是在将更多项目添加到listPanel时使contentPanel增长。

The problem I have is that when more components are added to listPanel the vertical scrollbar doesen't appear on my scrollpane. 我遇到的问题是,当更多组件添加到listPanel时,垂直滚动条不会出现在我的滚动窗格上。

The scrollbar will appear when the preferred size of the component added to the scrollpane is greater than the size of the scrollpane. 添加到滚动窗格的组件的首选大小大于滚动窗格的大小时,将显示滚动条。 When you add components dynamically you need to tell the scrollpane something has changed. 当您动态添加组件时,您需要告诉滚动窗格已更改的内容。 So you basic code should be: 所以你的基本代码应该是:

panel.add( subPanel );
panel.revalidate();

Or, because you are adding a panel to the sub panel, you may need to revalidate the scrollpane (I don't remember): 或者,因为您要将子面板添加到子面板,您可能需要重新验证滚动窗格(我不记得了):

panel.add( subPanel );
scrollPane.revalidate();   

The key is the revalidate() which tell the layout manager to recalculate its size. 关键是revalidate()告诉布局管理器重新计算其大小。

Use a different LayoutManager. 使用不同的LayoutManager。 One that will allow for vertical growth like BoxLayout. 可以像BoxLayout一样实现垂直增长。 Also remember that you can use multiple layouts and nest them inside of each other for different effects. 还要记住,您可以使用多个布局并将它们嵌套在一起以获得不同的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM