Thursday, 14 May 2015

Organizing Your Interface with Layouts

The traditional method for building a GUI has been to position various interface elements, such as buttons, at specific locations inside a window and then to allow the user to move the windows around. Java has had to explore new approaches to defining the layout of components because of the diversity of standards that it has to support. Although the AWT does let you specify the absolute location of components, it also gives you Layout Managers that let you define the relative placement of components that will look the same on a wide spectrum of display devices.
Although you can build your own Layout Manager, it's easiest to use one of the Managers that come with the AWT. In addition, freeware Layout Managers currently are available; these are discussed along with how to build your own Layout Manager, and more will be arriving in the future.

No Layout Manager

Although most containers come with a preset FlowLayout Manager, you can tell the AWT to use absolute positions with the following line of code:
setLayout(null);
This eliminates the default Layout Manager, or any other one that the container had been using, enabling you to position components by using absolute coordinates. Keep in mind, though, that absolute coordinates won't look the same on all platforms. Listing 17.26 shows a little applet that uses absolute coordinates and the resize and reshape methods from the Component

class to position and size a label and a text field.  If you don't use resize or reshape, you won't see the components. This approach to layouts can run into problems when the size of a font varies between platforms. You can use the FontMetrics class to figure out the size of a font relative to some standard size and then scale your absolute coordinates, but it's probably easier to just implement a custom Layout Manager.  

Listing 17.26. Positioning and sizing a label and text field.
import java.awt.*;
import java.applet.Applet;


public class no_layout extends Applet
{
    public void init()
    {
        Label a_label;
        TextField a_textfield;

        setLayout(null);
        a_label = new Label("A label");
        add(a_label);
        //change the size of the Label
        a_label.resize(40,50);
        a_textfield = new TextField(20);
        add(a_textfield);
        //set the size and position of the TextField
        a_textfield.reshape(20,40,140,10);
    }
}

No comments:

Post a Comment