如何使JScrollPane与嵌套的JPanels一起正常工作? [英] How do I make JScrollPane work properly with nested JPanels?

查看:75
本文介绍了如何使JScrollPane与嵌套的JPanels一起正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NetBeans在Java中构建Swing应用程序,但是布局存在问题.我的主框架包含一个JScrollPane,该JScrollPane包含一个称为contentPanelJPanel,而该JPanel又包含一个称为listPanelJPanel.程序启动时,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 JPanels 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆