Java GridLayout如何动态改变网格布局

Java GridLayout how to dynamically change grid layout

我正在尝试创建一个角色 sheet 程序,它根据框架的宽度排列 3 个面板。如果框架不是很宽,我希望面板垂直排列,但如果用户选择使框架更宽,我希望面板水平排列。

我还有一个 scrollPanel,上面排列着 3 个面板,因此将 scrollPanel 添加到 scrollPane。

我看到帖子说事件监听器可以工作,但其中大部分是针对按钮的,我需要在布局更改之前框架大小通过特定阈值。我看到其他推荐 html 的帖子,我现在认为没有必要。

因此在这张图片中,3 个面板是垂直排列的,并且可以滚动浏览。

    scrollPanel.add(leftPanel); //this is the yellow panel that is being added
    scrollPanel.add(centerPanel); //this one is farther down
    scrollPanel.add(rightPanel); //even farther down
    scrollPanel.setBackground(Color.CYAN);
    scrollPanel.setLayout(new GridLayout(0, 1)); //so here I would like to have an if statement or event swap the 0 and the 1.

总结:

您可以按如下方式更改 GridLayout:

gr.setRows(newR);
gr.setColumns(newC);
myFrame.validate();

其中 gr 是您在某处创建的布局,newR/newC 是 rows/columns 的新编号。

或者你可以说

gr=new GridLayout(newR, newC);
myFrame.setLayout(gr);

然后

if(myFrame.getWidth()>thershold) {

.. do the above

}