GridBagLayout无法显示组件。

huangapple go评论74阅读模式
英文:

GridBagLayout does not display a component

问题

我编写了一个用于显示圆形进度条的组件。当我将它放在BorderLayout中时,一切看起来都很好。

但是当使用GridBagLayout时,它无法显示出来。

p.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
p.add(north(), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
p.add(west(), gbc);
gbc.gridx = 1;
gbc.gridy = 1;
p.add(bar, gbc);

我不知道这是设置GridBagConstraints的问题还是其他原因。

英文:

I wrote a component to display a circular progressbar. When I put it in BorderLayout everything looks fine.

GridBagLayout无法显示组件。

But it can't be seen when a GridBagLayout is set.

GridBagLayout无法显示组件。

    p.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    p.add(north(), gbc);
    gbc.gridx = 0;
    gbc.gridy = 1;
    p.add(west(), gbc);
    gbc.gridx = 1;
    gbc.gridy = 1;
    p.add(bar, gbc);

I have no idea whether it is the problem of setting the GridBagConstraints or other reasons.

答案1

得分: 2

但是当设置GridBagLayout时,它是看不到的。

可能是因为您没有重写组件的getPreferredSize()方法,所以首选大小将为(0, 0)。

GridBagLayout将尝试以其首选大小显示组件。

我猜想您需要在添加组件时使用fill约束,以便它可以自动调整大小以填充单元格中可用的空间。阅读Swing教程中有关如何使用GridBagLayout的部分,获取更多信息和示例。

当我将它放在BorderLayout中时,一切看起来都很好。

当添加到BorderLayout的CENTER位置时,组件将被调整大小以填充可用的空间。

英文:

> But it can't be seen when a GridBagLayout is set.

Probably because you didn't override the getPreferredSize() method of your component so the preferred size will be (0, 0).

The GridBagLayout will attempt to display the component at its preferred size.

I would guess you would need to use the fill constraint when adding the component so it can be automatically resized to fill the space available in the cell. Read the section from the Swing tutorial on How to Use GridBagLayout for more information and examples.

> When I put it in BorderLayout everything looks fine.

When added to the CENTER of a BorderLayout the component will be resized to fill the space available.

huangapple
  • 本文由 发表于 2020年5月3日 18:47:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/61573185.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定