TextBox sample program in J2ME

By: Priya  

Unlike a TextField, a TextBox is a multiline, editable text area. TextBox is a kind of Screen, not an Item. Because a TextBox is a Displayable, you must create a MIDlet object to demonstrate its use; you can't place it in another Screen or Form, as you can with the components derived from Item.

The program below shows the partial source code of the TextBoxDemo class. The parts that are omitted are very similar structurally to the UIComponentDemo code, and relate to the attributes of the MIDlet.

You can see from the constructor that a TextBox is similar to a TextField, except that it's a
multiline text area. The arguments are the title, the initial text, the maximum number of characters
that it can hold, and the input constraints. The constraints are exactly the same constraints used by
the TextField class.

//Text boxes are screens and don't need a form in which to exist.
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;

This MIDlet demonstrates use of the MIDP UI TextBox
@see javax.microedition.lcdui.TextBox
public class TextBoxDemo extends MIDlet
implements CommandListener
private Command quit =
new Command("Exit", Command.EXIT, 1);
private static TextBoxDemo instance;
// The TextBox UI component.
private TextBox textBox;
// The maximum number of characters that the TextBox can
// hold.
private int MAX_SIZE = 100;
// The TextBox's initial text.
private String initialText =
"You can edit the contents of this TextBox";

public TextBoxDemo()
instance = this;
public void pauseApp()
public void destroyApp(boolean destroy)
textBox = null;
initialText = null;
instance = null;
void quit()
public void startApp()
textBox = new TextBox("A TextBox",

Returns the single instance of this class. Calling
this method before constructing an object will return
a null pointer.
@return an instance of this class.
public static TextBoxDemo getInstance()
return instance;
public void display()
public void commandAction(Command c, Displayable d)
if (c == quit)

Just as with other editable objects, you simply select the TextBox using the emulator's Select button and then edit the contents. You can navigate using the four arrow keys, erase characters using the Clear key, and input using either the keypad keys or your computer keypad when you're using an emulator. Of course, the program can also manipulate the content using a rich API that supports inserting, deleting, setting the maximum size, setting constraints, and so forth.

Archived Comments

Most Viewed Articles (in J2ME )

Latest Articles (in J2ME)

Comment on this tutorial