如何将多个组件添加到JFrame? [英] How to add multiple components to a JFrame?

查看:108
本文介绍了如何将多个组件添加到JFrame?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JFrame

我还有一个 Box 类,它扩展了 Component 即可。
这个box类有一个 paint 方法,它生成一个填充的矩形。

I also have a Box class which extends Component. This box class has a paint method which makes a filled rectangle.

当我将多个这些Box组件添加到我的JFrame时,当我在JFrame上调用 repaint 时,只显示最近添加的一个。

When I add multiple of these Box components to my JFrame, only the most recently added one is displayed when I call repaint on the JFrame.

我看了一下布局管理器,但是我我不确定那是我想要的。我想要的只是能够在屏幕上的任何地方制作一大堆矩形动画。

I took a look at the layout managers, but I am not sure that's what I want. All I want is to be able to make an animation of whole bunch of rectangles wherever I want on the screen.

(我也尝试创建一个面板,将面板添加到JFrame,然后将所有Box组件添加到面板。这也不起作用。)

(I also tried creating a panel, adding the panel to the JFrame, and then adding all the Box components to the panel. This did not work either).

提前致谢!

推荐答案

您有2个选择。

您可以更改框架的布局:

You can change the layout of your frame:

JFrame frame;
frame.setLayout(new FlowLayout());

现在,如果您添加多个框,它将显示在框架上。

Now, if you add more than one box, it will show up on the frame.

另一种选择是做你说的尝试。 (向框架添加面板)

The other option is to do what you said you tried. (Adding a panel to the frame)

JPanel pane = new JPanel();
frame.add(pane);
(add the boxes to 'pane')

另外,你应该小心调整的大小。您可能希望在创建 Box 的某个地方调用 setPreferredSize()。这将告诉Java在添加到布局时框的大小。

Also, you should be careful with the sizing of your Box. You will probably want a call to setPreferredSize() somewhere in the creation of the Box. This will tell Java what size to make the box when it is added to the layout.

您还应该看一下Java布局管理器教程。那里有很多很棒的信息。

You should also take a look at the Java Layout Manager Tutorials. There is lots of great info there.

还有一件事。框架上一次只显示一个框的原因是因为JFrame的布局管理器是 BorderLayout 。并且,当您在具有BorderLayout的组件上调用 add 时,该组件将自动添加到组件的中心。对 add 的后续调用将覆盖中心组件,只留下一个组件。

And, one more thing. The reason only one box at a time was being displayed on the frame was because JFrame's layout manager is BorderLayout. And, when you call add on a component that has a BorderLayout, the component is automatically added to the center of the component. Subsequent calls to add will overwrite the center component, leaving only one component in the middle.

这篇关于如何将多个组件添加到JFrame?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆