英文:
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.
But it can't be seen when a GridBagLayout
is set.
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论