如何使JScrollPane与嵌套的JPanels一起正常工作? [英] How do I make JScrollPane work properly with nested JPanels?
问题描述
我正在使用NetBeans在Java中构建Swing应用程序,但是布局存在问题.我的主框架包含一个JScrollPane
,该JScrollPane
包含一个称为contentPanel
的JPanel
,而该JPanel
又包含一个称为listPanel
的JPanel
.程序启动时,listPanel
为空,但是当用户与程序交互时,会向其中添加不可预测的较小的JPanel
.我已经使用NetBeans GUI生成器将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.
我的问题是,当更多组件添加到listPanel
时,垂直滚动条不会出现在我的滚动窗格中.我的滚动窗格的verticalScrollBarPolicy
设置为AS_NEEDED
,其viewportView
设置为contentPanel
.我想我需要做的是,当向listPanel
添加更多项目时,使contentPanel
增长.
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
.
推荐答案
我的问题是,当更多组件添加到listPanel时,垂直滚动条不会出现在我的滚动窗格中.
The problem I have is that when more components are added to listPanel the vertical scrollbar doesen't appear on my scrollpane.
当添加到滚动窗格的组件的首选大小大于滚动窗格的大小时,将显示滚动条.动态添加组件时,您需要告诉滚动窗格某些更改.所以您的基本代码应该是:
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();
关键是revalidate(),它告诉布局管理器重新计算其大小.
The key is the revalidate() which tell the layout manager to recalculate its size.
这篇关于如何使JScrollPane与嵌套的JPanels一起正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!