Lesson 5.6 Panels and Layouts
Using Panels and Layout Managers
Many of you have found working with Java applets frustrating because you can't precisely position your components in the same way you can with Visual Basic, for instance.
It's true that Java doesn't lend itself well to WYSIWYG [What You See Is What You Get] layout because the actual program may run on different hardware than the hardware that you design it on. Like HTML pages, Java programs should not be tied to the hardware that they were created on.
In Java, instead of positioning items visually, pixel-by-pixel, you use a layout manager object to arrange and size your components on the screen according to a set of rules.
The FlowLayout Class
The default (built-in) layout manager for applets is called FlowLayout. FlowLayout works by asking each component how big it wants to be, sizing the component accordingly, and then adding components to the screen one after another, much like text is printed on the page.
If a component won’t fit on a row, then FlowLayout starts a new row. FlowLayout layout managers come in three different varieties, left-aligned, right-aligned, and center aligned. The default version--the one you get if you don't do anything--is center-aligned.
Changing Layouts
To use a different layout manager, even if it is just a different variety of FlowLayout, you call the Container class method, setLayout(). Since the Applet class is a subclass of Container, you can send the setLayout() message to your applet.
When you call setLayout(), you pass a layout manager object, which you can construct in your init() method like this:
FlowLayout mgr =
new FlowLayout(FlowLayout.LEFT);
setLayout( mgr ); |
Here's a program that lets you exercise the different versions of FlowLayout, to see how they behave.
|
TestFlow.java
|
// Test the FlowLayout class
import java.awt.*;
import java.applet.*;
public class TestFlow extends Applet
{
Button addBtn = new Button("Add");
Button leftBtn = new Button("Left");
Button rightBtn = new Button("Right");
Button centerBtn = new Button("Center");
FlowLayout mgr;
int nButtons = 4;
public void init()
{
add(addBtn);
add(leftBtn);
add(rightBtn);
add(centerBtn);
}
public boolean action(Event ev, Object o)
{
if (ev.target == addBtn)
{
add(new Button("Button # "+nButtons++));
}
else if (ev.target == leftBtn)
{
mgr = new FlowLayout(FlowLayout.LEFT);
setLayout(mgr);
}
else if (ev.target == rightBtn)
{
mgr = new FlowLayout(FlowLayout.RIGHT);
setLayout(mgr);
}
else if (ev.target == centerBtn)
{
mgr = new FlowLayout(FlowLayout.CENTER);
setLayout(mgr);
}
invalidate();
validate();
return true;
}
} |
Examining TestFlow
The TestFlow applet has several interesting features that you should examine.
- The applet first creates four Buttons named addBtn, leftBtn, centerBtn, and rightBtn, and then adds them to its surface.
- It uses the Java 1.0 action() method, which you learned about in Lesson 5.5, "Action".
- Inside the action() method, a ladder-style if-else-if statement takes a separate action for each Button pressed.
- If the Button pressed is the addBtn, then a new Button is added to the applet.
- If the Button pressed is the leftBtn, rightBtn, or centerBtn, then an appropriate FlowLayout layout manager is constructed and applied to the applet, using setLayout().
- Once the changes have been made to the applet, it is told to "rearrange" all of its Buttons, using the "magic" incantation:
invalidate();
validate(); |
- These messages force the layout manager to layout the applet and force any newly added Buttons to appear as well.
Running TestFlow
To run the TestFlow applet, first add a few new Button objects by pressing the "Add" button. Then, arrange them in different ways by clicking on the "Left", "Right", or "Center" buttons.
BorderLayout
One alternative to FlowLayout is the BorderLayout layout manager. BorderLayout divides your applet space into five different regions named "North", "South", "East", "West", and "Center". Each of these regions can hold only a single component, and the component "swells up" to take all of the space available in that region.
You create a BorderLayout layout manager just like you do any other object--using a constructor. BorderLayout has several different constructors, but the default constructor is fine for now:
| BorderLayout bl = new BorderLayout(); |
Once you've constructed a BorderLayout layout manager, you can instruct your applet to use it by sending the setLayout() message, just as you did for FlowLayout:
| setLayout(bl); // Use new BorderLayout |
Adding Components
Because BorderLayout has several different regions, you have to use a special form of add() that tells the layout manager where to place the components. There are three ways to do this:
- In Java 1.0 [if you are using the action() method], use:
| add(direction, component); |
where direction is "North", "South", "East", "West", or "Center", and component is your Button or Label.
- In Java 1.1, you use the same syntax, but reverse the position of direction and component
- In Java 1.1 and Java 2, you can use the five constants BorderLayout.EAST, BorderLayout.WEST, BorderLayout.NORTH, BorderLayout.SOUTH and BorderLayout.CENTER in place of typing in the String literals.
The advantage of using the constants shown in method three, is that the compiler will warn you if you spell one incorrectly. If you use the literals, however, and spell "North" like "Nothr", the compiler doesn't catch it, but your program crashes with an "Unknown Constraint" error when it runs.
TestBorder.java
Here's an example that adds four buttons to the top, left, right, and bottom, and places another button in the center:
|
Adding Components to BorderLayout
|
add("North", new Button("North"));
add("South", new Button("South"));
add("East", new Button("East"));
add("West", new Button("West"));
add("Center", new Button("Center")); |
When you run the applet, it looks like this:
Introducing Panels
BorderLayout solves some layout problems, but creates a few new ones. For instance, you might want to place a button at the bottom of your applet, but not have it swell up like a balloon. Or, you may want to add several buttons to the bottom or top of your screen, but BorderLayout only allows one component in each of its five positions. That's when you need a Panel object.
A Panel object acts like a container for other components. You can add objects to a Panel just the same way you add them to an applet. [In fact, the Applet class is a specialized subclass of Panel.]
The default layout manager for a Panel is FlowLayout so that objects are sized naturally. Once you've added all your buttons and labels to your Panel, you can then add the Panel to your applet that uses BorderLayout. The result? The Panel swells up, but the components it contains retain their natural size.
Here's a piece of code that shows you how to add several buttons to the top of an applet to create a "toolbar".
public void init()
{
setLayout(new BorderLayout());
// 1. Create a Panel object
Panel p = new Panel();
// 2. Add two Buttons to the Panel
p.add(new Button("One"));
p.add(new Button("Two"));
// 3. Add your Panel to the applet
add("North", p);
} |
Introducing TextArea
The TextField class allows you to enter a single line of text. Java also has the TextArea class that allows you to enter or display several lines of text.
The TextArea class is very useful when you need to create a more extensive "dialog" with the user than a single line of text allows. You can use the TextArea to display instructions, and to keep the user informed concerning the progress of your application. You'll use a TextArea for this purpose in the homework assignment for this unit.
To create a TextArea object, you can use several different constructors, but the most useful is the one allows you to specify the number of rows and columns that you'd like displayed.
For instance, here's an example that creates a TextArea big enough to hold eight lines of text, with each line of text [roughly] 40 characters wide.
| TextArea ta = new TextArea(8, 40); |
Unfortunately, when working with BorderLayout, the TextArea swells up like every other component, so there's really no benefit to specifying a specific size--especially if you are going to place your TextArea in the "Center" position, as is often the case.
TextArea Operations
Once you've created a TextArea object, you can tell it to do several things. If you want to clear the TextArea of all text, you can write:
where the argument to setText() is the empty String. [Two pairs of double-quotes, with no intervening spaces.]
You can add text to the end of a TextArea by using the append() method in Java 1.1, and the appendText() method in Java 1.0. like this:
ta.append("Some text\n"); // 1.1
ta.appendText("Some text\n"); // 1.0 |
Here's an example program, TestTA.java, that puts together several of the different skills used in this section. It uses a BorderLayout, has a TextArea in the center, has a toolbar built using a Panel at the top, and it uses the Java 1.0 action() method.
Something to Talk About
Can an applet that uses BorderLayout include a Panel that also uses BorderLayout? Why don't you find out.
Using the code from TestBorder.java as a starting point, show us the code you'd write in the init() method to create an applet that looks like this:
This is the last section of this lesson.
|