Ask Questions?

View Latest Questions


 
 

Layouts
Posted on: July 26, 2006 at 12:00 AM
Create a new layout object and use the container's setLayout method to set the layout.

Java Notes

Layouts

Layouts tell Java where to put components in containers (JPanel, content pane, etc). Every panel (and other container) has a default layout, but it's better to set the layout explicitly for clarity.

Create a new layout object (using one of its constructors) and use the container's setLayout method to set the layout. Each layout has its own way to resize components to fit the layout, and you must become familiar with these.

Tools. Creating your layouts by hand is simple for the simple layouts, but for really good layouts using the difficult GridBagLayout, you might want to use a program to help you. A good review of some of these programs is at Java GUI Builders (www.fullspan.com/articles/java-gui-builders.html) by Mitch Stuart.

General advice

.
  • Initial Iterations. To quickly get the first iterations of a program running, use FlowLayout. The result is often ugly, but if there are only a few components, it's quick. FlowLayout is rarely the correct layout to use in a finished program.
  • Simple programs. BorderLayout is often a good layout for simple programs. More complicated layouts can often be nesting BorderLayouts within other BorderLayouts. This and FlowLayout are the most important layouts for beginners.
  • Grids of equal sized elements (eg, a calculator keypad), can be created with with GridLayout.
  • Single Rows or colums of components are sometimes best done with BoxLayout.
  • More complicated layouts may require GridBagLayout. Getting a GridBagLayout to work correctly can be time-consuming, but it produces excellent results.

More notes

  • FlowLayout - left to right, top to bottom. Good for initial testing. FlowLayout does not respect preferred size information, so it may make variable size elements (eg, a graphics panel) extremely small.
  • <