Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

java - How to add multiple components to a JFrame?

I have a JFrame.

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

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.

(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).

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have 2 choices.

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')

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.

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...