Documentation

The Java™ Tutorials
Hide TOC
Solving Common Layout Problems
Trail: Creating a GUI With Swing
Lesson: Laying Out Components Within a Container

Solving Common Layout Problems


Note: 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?


Note: 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