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

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

问题描述

我有一个 JFrame.

我还有一个 Box 类,它扩展了 Component.这个盒子类有一个 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).

提前致谢!

推荐答案

你有两个选择.

您可以更改框架的布局:

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 的大小.您可能希望在创建 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天全站免登陆