Making a List

It is extremely bad form to use System.out.println() in an applet. On some systems this may not work at all. However it has the advantage of being familiar and easy. For more serious work you should actually draw your text in the applet window. There are at least three different ways to do this. For our purposes the one that makes the most sense is to use a List.

A List is a scrolling list of Strings defined in java.awt.List. We create a new List with new, just as we create any other Object. The specific constructor we use asks for an int that’s the number of visible lines and a boolean that tells whether or not multiple selections are allowed. We’ll ask for 25 lines and no multiple selections.

List theList;
theList = new List(25, false);

We add Strings to the list by using the addItem method of the List we’re adding to like so:

theList.addItem(”This is a list item”);

Finally we need to actually add this List to our applet (more precisely the applet’s container). We do this with the line

add(theList);

in the init method. That’s all. We can use the same applet we used before with these simple changes.

import java.applet.Applet;
import java.awt.*;

public class EventList extends Applet {

List theList;

public void init() {
theList = new List(25, false);
add(theList);
theList.addItem(”init event”);
}

public void paint(Graphics g) {
theList.addItem(”paint event”);
}

public void start() {
theList.addItem(”start event”);
}

public void destroy() {
theList.addItem(”destroy event”);
}

public void update(Graphics g) {
theList.addItem(”update event”);
}

public boolean mouseUp(Event e, int x, int y) {
theList.addItem(”mouseUp event”);
return false;
}

public boolean mouseDown(Event e, int x, int y) {
theList.addItem(”mouseDown”);
return false;
}

public boolean mouseDrag(Event e, int x, int y) {
theList.addItem(”mouseDrag event”);
return false;
}

public boolean mouseMove(Event e, int x, int y) {
theList.addItem(”mouseMove event”);
return false;
}

public boolean mouseEnter(Event e, int x, int y) {
theList.addItem(”mouseEnter event”);
return false;
}

public boolean mouseExit(Event e, int x, int y) {
theList.addItem(”mouseExit event”);
return false;
}

public void getFocus() {
theList.addItem(”getFocus event”);
}

public void gotFocus() {
theList.addItem(”gotFocus event”);
}

public void lostFocus() {
theList.addItem(”lostFocus event”);
}

public boolean keyDown(Event e, int x) {
theList.addItem(”keyDown event”);
return true;
}

}

We’ll talk more about containers, Lists, and applet components in a later section.

Comments are closed.