如何使 JScrollPane 与嵌套 JPanel 一起正常工作?
我正在使用 NetBeans 在 Java 中构建 Swing 应用程序,但我遇到布局问题。我的主框架包含一个 JScrollPane
,其中包含一个名为 contentPanel
的 JPanel
,而后者又包含一个名为 JPanel
列表面板。当程序启动时,listPanel
是空的,但是当用户与程序交互时,会向其中添加不可预测数量的较小 JPanel
。我使用 NetBeans GUI 构建器将 listPanel
的顶部边缘对齐到 contentPanel
的顶部,底部边缘也是如此。
我遇到的问题是,当更多组件添加到 listPanel
时,垂直滚动条不会出现在我的滚动窗格上。我的滚动窗格的 verticalScrollBarPolicy
设置为 AS_NEEDED
,其 viewportView
设置为 contentPanel
。我认为我需要做的是当更多项目添加到 listPanel
时使 contentPanel
增长。
I'm building a Swing application in Java using NetBeans and I have a problem with layout. My main frame contains a JScrollPane
which contains a JPanel
called contentPanel
which in turn contains a JPanel
called listPanel
. 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. 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.
The problem I have is that when more components are added to listPanel
the vertical scrollbar doesen't appear on my scrollpane. The verticalScrollBarPolicy
of my scrollpane is set to AS_NEEDED
and its viewportView
is set to contentPanel
. What I think I need to do is to make contentPanel
grow when more items are added to listPanel
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当添加到滚动窗格的组件的首选大小大于滚动窗格的大小时,就会出现滚动条。当您动态添加组件时,您需要告诉滚动窗格某些内容发生了变化。所以你的基本代码应该是:
或者,因为你要向子面板添加一个面板,所以你可能需要重新验证滚动窗格(我不记得了):
关键是 revalidate() ,它告诉布局管理器重新计算其尺寸。
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:
Or, because you are adding a panel to the sub panel, you may need to revalidate the scrollpane (I don't remember):
The key is the revalidate() which tell the layout manager to recalculate its size.
使用不同的布局管理器。一种像 BoxLayout 一样允许垂直增长的布局。另请记住,您可以使用多个布局并将它们嵌套在一起以获得不同的效果。
Use a different LayoutManager. One that will allow for vertical growth like BoxLayout. Also remember that you can use multiple layouts and nest them inside of each other for different effects.