Java Reference
In-Depth Information
The program produces the following graphical output:
This program's output is probably not what you expected. The first button isn't
visible; it's hidden beneath the second button, which has been stretched to fill the
entire frame. Let's explore the cause of this problem and learn how to solve it.
Changing a Frame's Layout
The problem in the previous program has to do with the layout of the components:
the way that they are positioned, sized, and so on. We didn't tell the frame how to lay
out the buttons, so it used a default behavior that positions each component in the
center of the frame and extends it to fill the entire frame's space. When multiple com-
ponents are added to the frame, the program places the last component on top and
extends it to fill all the onscreen space.
Each button has size and location properties, but setting these in our code won't
fix the problem. To fix the window's appearance, we must use an object called a
layout manager.
Layout Manager
A Java object that determines the positions, sizes, and resizing behavior of
the components within a frame or other container on the screen.
The frame has a layout manager object that it uses to position all the components
inside it. Even if we set the positions and sizes of the buttons, the frame's layout
manager will set them back to its default values. To position the components in a dif-
ferent way, we must set a new layout manager for the frame and use it to position the
components.
Java contains many layout manager classes in its java.awt package, so make sure
to import that package (along with javax.swing for the JFrame and other compo-
nent classes):
import java.awt.*; // for layout managers
import javax.swing.*; // for GUI components
The default type of layout manager for a JFrame is called a BorderLayout ,
which we'll explore later in this chapter. If we want the buttons to flow in a left-to-
right order instead, we can set the frame to use a different layout manager called
 
Search WWH ::




Custom Search