在我的GUI应用程序中,我有几个JPanel在程序运行的不同时间点被实例化,某些操作会导致其中一个在滚动面板中显示:
mViewport.setViewportView(currentPanel);
问题是,我的面板使用网格包布局完成,它的行为是在其所在的JScrollPane中心对齐。这会使GUI看起来很奇怪。
有人知道强制网格包布局面板左上对齐的方法吗?
谢谢!
编辑
请注意,我在此询问整个面板在其滚动窗格内的对齐方式,而不是面板内组件的对齐方式。
在我的GUI应用程序中,我有几个JPanel在程序运行的不同时间点被实例化,某些操作会导致其中一个在滚动面板中显示:
mViewport.setViewportView(currentPanel);
GridBagConstraints
中)。这会使组件“推”来占用更多可用空间(如果没有权重,组件只会占用所需空间,并且面板将居中于可用空间)。在一些试验之后,我找到了自己问题的解决方案:
设置权重似乎能够影响使用GridBagLayout
的JPanel
中组件的对齐方式。然而,它没有影响JScrollPane
内JPanel
的对齐方式。
我找到了一个相当简单的解决方案,即不要像之前的代码那样直接将JPanel
放入JScrollPane
中:
if (currentPanel != mCurrentPanel)
{
mViewport.setViewportView(currentPanel);
}
相反地,应该在JScrollPane
内部放置一个“外部”JPanel
,并将其设置为使用FlowLayout
。然后,当我想要切换面板时,我会移除旧的面板,并将面板放置在“外部”面板中。
if (currentPanel != mCurrentPanel)
{
if (mCurrentPanel != null)
{
mOuterPanel.remove(mCurrentPanel);
}
mCurrentPanel = currentPanel;
mOuterPanel.add(mCurrentPanel);
}