gpt4 book ai didi

java - Swing:GridBagLayouts anchor 无法嵌套在其他 GridBagLayout 中

转载 作者:行者123 更新时间:2023-12-02 04:22:33 27 4
gpt4 key购买 nike

我正在将第一个 GridBagLayout 设置为主 JPanel。在此面板中,还使用此布局添加了其他十个面板(外部约束)。子面板包含大量文本,应使用新布局和 innerConstraints 将其放置在 WEST 位置。但他们居中。

经过一些测试,我发现文本/图像放置在西边,但前提是outerConstraints 没有水平填充白色面板。问题是,我无法删除此命令,因为我需要每个面板都具有相同的宽度。

是否有可能允许 outerConstraints 填充并使其嵌套的 GridBagLayout 将文本定位在左侧?

setLayout(new GridBagLayout());

GridBagConstraints outerConstraints = new GridBagConstraints();
outerConstraints.insets = new Insets(5, 5, 5, 5);
outerConstraints.fill = GridBagConstraints.HORIZONTAL; // seems to be reason, but needed.

for (int i = 0; i < 10; i++) {

outerConstraints.gridx = i % 2;
outerConstraints.gridy = i / 2;

JPanel agentVisitCard = new JPanel();
add(agentVisitCard, outerConstraints);

GridBagConstraints innerConstraints = new GridBagConstraints();
innerConstraints.anchor = GridBagConstraints.WEST; //fails
innerConstraints.insets = new Insets(5, 5, 5, 5);

GridBagLayout layout = new GridBagLayout();
agentVisitCard.setLayout(layout);

(...)

JLabel label = new JLabel("Agent " + (i + 1) + ":");

innerConstraints.gridx = 0;
innerConstraints.gridy = 0;

agentVisitCard.add(label, innerConstraints);

代理 3 未向左对齐: enter image description here

最佳答案

anchor 不起作用的原因是组件没有重量。否则,给予组件的面积只是所需的最小尺寸,即组件本身的尺寸,而不会更大。

这里引用 swing tutorials (在weightx,weighty部分下)解释它:

Unless you specify at least one non-zero value for weightx or weighty, all the components clump together in the center of their container. This is because when the weight is 0.0 (the default), the GridBagLayout puts any extra space between its grid of cells and the edges of the container.

默认情况下,weightx 和weighty 为0,这就是它不适合您的原因。由于您只想水平锚定它,因此将weightx 设置为非零值可以使其工作。如果您想要垂直 anchor ,则还需要设置权重。

如何使用weightx和weighty值的解释如下:

Generally weights are specified with 0.0 and 1.0 as the extremes: the numbers in between are used as necessary. Larger numbers indicate that the component's row or column should get more space.

尽管他们建议使用 0.0 到 1.0 之间的值,但这不是必需的。任何 double 值都可以。如果有多个组件,重要的是组件之间的重量比。

关于java - Swing:GridBagLayouts anchor 无法嵌套在其他 GridBagLayout 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32592709/

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