gpt4 book ai didi

java - 防止 FlowLayout 垂直居中

转载 作者:行者123 更新时间:2023-12-01 18:17:14 25 4
gpt4 key购买 nike

我有一个使用 FlowLayout 布局管理器的 JPanel,并且包含不同大小的组件。

编辑:我想使用 FlowLayout,因为它允许组件在调整容器大小并且它们不再彼此相邻时换行。

下图描述了 FlowLayout 在不同组件上的垂直对齐方式:

How the FlowLayout is aligning the components

如何修改 FlowLayout 以对齐组件顶部,如下图所示:

How I would like the FlowLayout to align the components

这是问题的代码示例:

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel flowPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
frame.getContentPane().add(flowPanel);

JButton firstComp = new JButton("First");
firstComp.setPreferredSize(new Dimension(200, 300));
flowPanel.add(firstComp);

JButton secondComp = new JButton("Second");
secondComp.setPreferredSize(new Dimension(160, 180));
flowPanel.add(secondComp);

frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

最佳答案

FlowLayout 本身不支持对齐,因此除非您确实需要它的多行行为,否则最好使用支持对齐的布局管理器(例如 BoxLayout)。不过,通过使用 FlowLayout 可以做到的基线对齐,可以在一定程度上解决这个问题:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Align {
private static final int PREF_HEIGHT = 100;

Align() {
JFrame frame = new JFrame("Align test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel bg = new JPanel();
((FlowLayout) bg.getLayout()).setAlignOnBaseline(true);
frame.add(bg);
JPanel left = new JPanel();
left.setBackground(Color.BLUE);
left.setPreferredSize(new Dimension(100, PREF_HEIGHT));
bg.add(left);

JPanel right = new JPanel() {
@Override
public int getBaseline(int width, int height) {
return PREF_HEIGHT;
}
};
right.setBackground(Color.GREEN);
right.setPreferredSize(new Dimension(100, 50));
bg.add(right);

frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Align();
}
});
}
}

结果:

enter image description here

不幸的是,这并不是完美无缺的。首先是获取基线的半神奇方法,这取决于面板中其他组件的高度。其次,当组件自行移动到一行时,FlowLayout 将为组件保留太多空间 - 它占用的空间量与其他面板一样高。 (如果您在 right 之后添加更多面板,就可以看到这一点)。那时,使用嵌套布局来放置较小的面板可能比弄乱基线更容易。

基本上,您最好使用其他布局管理器,除非您确实无法避免 FlowLayout

关于java - 防止 FlowLayout 垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28877187/

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