Page 732 - Introduction to Programming with Java: A Problem Solving Approach
P. 732
698 Chapter 17 GUI Programming—Component Layout, Additional GUI Components
Layout Changes
Normally, setLayout is called just once in a program—when the program initially lays out its compo- nents. But if there’s a need to dynamically adjust the layout scheme, call setLayout again. For example, if you want the user to be able to adjust text alignment, add Align Left, Align Center, and Align Right buttons. Add a listener to each button. In each listener, call setLayout. This would be the listener for the Align Left button:
private class Listener implements ActionListener
{
}
Apago PDF Enhancer
setLayout(new FlowLayout(FlowLayout.LEFT));
validate();
public void actionPerformed(ActionEvent e)
{
} // end actionPerformed
// end class Listener
Note the validate method in the above code fragment. It causes the layout manager to regenerate the component layout. If your window is visible (i.e., you’ve called setVisible(true)), and you attempt to change its layout in some way, you’ll need to call validate to make the change take effect. These method calls attempt to change the layout:
• setLayout—Change the window’s layout manager. • add—Addacomponenttothewindow.
• setSize—Change the window’s size.
If your window is already visible and you call one of those methods, don’t forget to call validate after- wards. If you have a series of such calls, there’s no need to have separate validate method calls. Putting one validate method call at the end works fine.
17.4 BorderLayoutManager
The FlowLayout manager is popular because it’s easy to use. Just add components to its container and that’s it. Sometimes all you need is something simple. But be aware that the FlowLayout manager doesn’t provide much control over where components are positioned. Using a FlowLayout manager, you can position components horizontally (left, right, or center), but you can’t position components vertically. If you