java的网格包布局:避免居中对齐网格、布局、java

2023-09-11 07:49:03 作者:执酒共酌

在我的GUI应用程序中,我有一个是我的程序运行过程中实例化的不同点几JPanels,和某些行为会导致他们中的一个将显示在滚动窗格:

In my GUI application, I have several JPanels that are instantiated at various points during the running of my program, and certain actions will cause one of them to be displayed in a scroll pane:

mViewport.setViewportView(currentPanel);

麻烦的是,我的面板都是使用网格袋布局,以及该行为是JScrollPane的是内内的中心本身。这使得界面看起来很怪异。

The trouble is, that my panels are done using Grid Bag Layouts, and the behaviour of that is to center itself within the JScrollPane it is inside of. This make the GUI look weird.

任何人都知道的一种方式来强制网格包布局面板顶部,左对齐?

Anyone know of a way to force a grid bag layout panel to top-left align?

谢谢!

修改

请注意,在这里,我问它的滚动窗格中整个面板的排列,而不是对面板中的组成部分。

Note that here I am asking about the alignment of the entire panel within its scroll pane, not about the components within the panel.

推荐答案

我发现经过一番​​摆弄周围的解决方案,以我自己的问题:

I found a solution to my own question after some fiddling around:

设置的权重似乎能影响在的JP​​anel 为其的GridBagLayout 中使用的组件的排列。然而,它并没有对的排列效果的的JP​​anel JScrollPane的

Setting weights appears to be able to affect alignment of the components within the JPanel for which the GridBagLayout was used. However, it didn't have an effect on the alignment of the JPanel within the JScrollPane.

我发现了一个相当简单的解决方案,这是为不可以投放的JP​​anel 直接内的 JScrollPane的,因为我在做我的前面code:

I found a rather simple solution, which is to not put the JPanel directly inside of the JScrollPane, as I was doing with my earlier code:

if (currentPanel != mCurrentPanel)
{
    mViewport.setViewportView(currentPanel);
}

...而是把一个"外" 的JP​​anel JScrollPane的,并设置为使用的FlowLayout 。然后,当我想开关面板,我删除了旧的,并放置在面板中的"外"面板。

... but instead to put an "outer" JPanel inside the JScrollPane, and set that to use a FlowLayout. Then when I want to switch panels, I remove the old and place the panel within the "outer" panel.

if (currentPanel != mCurrentPanel)
{
    if (mCurrentPanel != null)
    {
        mOuterPanel.remove(mCurrentPanel);
    }
    mCurrentPanel = currentPanel;
    mOuterPanel.add(mCurrentPanel);
}

该方法的工作,而不是每个许多面板我有相当好,因为这意味着我只需要在一个类实现改变。

This approach worked rather well, because it meant I only had to effect changes in one class, instead of each of the many panels I had.