文档

Java™ 教程-Java Tutorials 中文版
解决常见布局问题
Trail: Creating a GUI With JFC/Swing
Lesson: Laying Out Components Within a Container

解决常见布局问题


注意: This lesson covers writing layout code by hand, which can be challenging. If you are not interested in learning all the details of layout management, you might prefer to use the GroupLayout layout manager combined with a builder tool to lay out your GUI. One such builder tool is the NetBeans IDE. Otherwise, if you want to code by hand and do not want to use GroupLayout, then GridBagLayout is recommended as the next most flexible and powerful layout manager.

If you are interested in using JavaFX to create your GUI, see Working With Layouts in JavaFX.

Problem:How do I specify a component's exact size?


注意: No matter how you specify your component's size, be sure that your component's container uses a layout manager that respects the requested size of the component. The FlowLayout and GridBagLayout managers use the component's preferred size (the latter depending on the constraints that you set), but BorderLayout and GridLayout usually do not. The BoxLayout manager generally uses a component's preferred size (although components can be larger), and is one of the few layout managers that respects the component's maximum size.

Problem:My component does not appear after I have added it to the container.

Problem:My custom component is being sized too small.

If you do not see your problem in this list, see Solving Common Component Problems.


Previous page: Doing Without a Layout Manager (Absolute Positioning)
Next page: Questions and Exercises: Laying Out Components within a Container