gpt4 book ai didi

Java Swing : FlowLayout JPanels are sitting next to each other?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:11:24 25 4
gpt4 key购买 nike

我在 JFrame 上绘制了三个 JPanel。这些目前都设置为使用默认的 FlowLayout。我希望这些在单个列中一个一个地放在另一个之上。

但是,我发现它们在同一条线上彼此相邻 float ,只要它们中的组件。

FlowLayout JPanel 的自然宽度是其内容的总和吗?如果是这样,有没有办法强制该区域的宽度为 JFrame 的宽度?

有趣的是,我发现,如果“顶部”和“底部”面板的内容跨越 JFrame 的整个宽度,而“中间”面板留空,则“中间”面板会创建一个空间介于两者之间,很像 html 的旧“

谢谢,

最佳答案

正如 Jim 所说,如果您需要线性对齐组件,BoxLayout 是正确的选择。

这是一个例子:

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
*
* @author nicholasdunn
*/
public class BoxLayoutExample extends JPanel {

public BoxLayoutExample() {
JPanel topPanel = new JPanel();
JPanel middlePanel = new JPanel();
JPanel bottomPanel = new JPanel();

topPanel.setBorder(BorderFactory.createEtchedBorder());
middlePanel.setBorder(BorderFactory.createEtchedBorder());
bottomPanel.setBorder(BorderFactory.createEtchedBorder());

topPanel.add(new JLabel("Top"));
middlePanel.add(new JLabel("Middle"));
bottomPanel.add(new JLabel("Bottom"));

BoxLayout boxLayout = new BoxLayout(this, BoxLayout.PAGE_AXIS);
setLayout(boxLayout);
add(topPanel);
add(middlePanel);
add(bottomPanel);

}

public static void main(String[] args) {
JFrame frame = new JFrame("");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new BoxLayoutExample();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
}

alt text

您最好通读 introduction to layout managers了解 LayoutManagers 的基础集。当需要进行复杂布局时,请使用 MigLayout而不是尝试学习 GridBagLayout - 你会感谢我的。

关于Java Swing : FlowLayout JPanels are sitting next to each other?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4244476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com