Java Reference
In-Depth Information
Although the layout managers provide basic layout options, quite flexible layouts can be achieved by
nesting containers and thus combining layout managers. For example, in order to show a list of aligned
labels and input elements, two panels with a grid layout can be placed in the west and center areas of a
border layout. If the number of labels in the west grid matches the number of input components in the
center grid, the labels and input components are vertically aligned automatically. Furthermore, the
space for the labels is limited to the minimum, whereas the input components get all the remaining
space. Dialog buttons are usually placed in a panel with flow layout in the south area of the dialog.
As a sample application demonstrating nested Panel s (and BorderLayout and FlowLayout ),
you will implement a PDA user interface for the British Museum Algorithm. Basically, the idea behind
the British Museum Algorithm is that, given a set of monkeys typing on typewriters, eventually all
existing literature in the world would be generated—you just need to wait long enough. We simulate a
monkey typing a line by randomly generating characters. The user interface should consist of a button
for generating a sentence, an exit button, and a list of sentences generated so far. How can we distribute
the screen space in a way that the buttons are displayed and all the remaining space goes to the list of
sentences? The answer is quite simple: We put the list in the center of a BorderLayout , which gets
all remaining space not taken by the other regions. In the south area, we put a Panel with
FlowLayout , where we add the buttons. Fortunately, BorderLayout is the default layout of
frames and FlowLayout is the default layout of Panel s, so we do not need to explicitly set a layout.
(We will do so in an extended example.)
Listing 4.3 shows the implementation of the application. The components are created with the
corresponding variables and arranged in the constructor of the MIDlet. The call of the pack() method
performs the layout of the components and adjustment of the frame size. (Some PDAs might have a
fixed frame size covering the whole screen.) The actionPerformed() method terminates the
application or generates a new sentence by calling generateSentence() , depending on the button
pressed. Figure 4.3 shows the actual layout of the application on a Palm Pilot.
Figure 4.3. The typing monkeys application.
Listing 4.3 GhostWriter.java —The Typing Monkeys Source Code
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.microedition.midlet.*;
class GhostWriter extends MIDlet implements ActionListener {
List list = new List();
Frame frame = new Frame ("The Monkeys type....");
 
 
Search WWH ::




Custom Search