Java/J2ME/TextBox TextField

Материал из Java эксперт
Перейти к: навигация, поиск

GUI Test in MIDlet

/*
Learning Wireless Java
Help for New J2ME Developers
By Qusay Mahmoud
ISBN: 0-596-00243-2
*/
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
public class GuiTests extends MIDlet implements CommandListener {
    // display manager
    Display display = null;
    
    // a menu with items
    List menu = null; // main menu
    // list of choices
    List choose = null;
    // textbox
    TextBox input = null;
    // ticker
    Ticker ticker = new Ticker("Test GUI Components");
    // alerts
    final Alert soundAlert = new Alert("sound Alert");
    // date
    DateField date = new DateField("Today"s date: ", DateField.DATE);
    // form
    Form form = new Form("Form for Stuff");
     
    // gauge
    Gauge gauge = new Gauge("Progress Bar", false, 20, 9);
    // text field
    TextField textfield = new TextField("TextField Label", "abc", 50, 0);
    // command
    static final Command backCommand = new Command("Back", Command.BACK, 0);
    static final Command mainMenuCommand = new Command("Main", Command.SCREEN, 1);
    static final Command exitCommand = new Command("Exit", Command.STOP, 2);
    String currentMenu = null;
    // constructor.
    public GuiTests() {
    }
    /**
     * Start the MIDlet by creating a list of items and associating the
     * exit command with it.
     */
    public void startApp() throws MIDletStateChangeException {
      display = Display.getDisplay(this);
      // open a db stock file
      menu = new List("Test Components", Choice.IMPLICIT);
      menu.append("Test TextBox", null);
      menu.append("Test List", null);
      menu.append("Test Alert", null);
      menu.append("Test Date", null);
      menu.append("Test Form", null);
      menu.addCommand(exitCommand);
      menu.setCommandListener(this);
      menu.setTicker(ticker);
      mainMenu();
    }
    public void pauseApp() {
      display = null;
      choose = null;
      menu = null;
      ticker = null;
      form = null;
      input = null;
      gauge = null;
      textfield = null;      
    }
    public void destroyApp(boolean unconditional) {
      notifyDestroyed();
    }
    // main menu
    void mainMenu() {
      display.setCurrent(menu);
      currentMenu = "Main"; 
    }
    /**
     * Test the TextBox component.
     */
    public void testTextBox() {
      input = new TextBox("Enter Some Text:", "", 10, TextField.ANY);
      input.setTicker(new Ticker("Testing TextBox"));
      input.addCommand(backCommand);
      input.setCommandListener(this);
      input.setString("");
      display.setCurrent(input);
      currentMenu = "input";
    }
   
    /**
     * Test the List component.
     */
    public void testList() {
        choose = new List("Choose Items", Choice.MULTIPLE);
        choose.setTicker(new Ticker("Testing List"));
        choose.addCommand(backCommand);
        choose.setCommandListener(this);
        choose.append("Item 1", null);
        choose.append("Item 2", null);
        choose.append("Item 3", null);
        display.setCurrent(choose);
        currentMenu = "list"; 
   }
   /**
    * Test the Alert component.
    */
   public void testAlert() {
      soundAlert.setType(AlertType.ERROR);
      //soundAlert.setTimeout(20);
      soundAlert.setString("** ERROR **");
      display.setCurrent(soundAlert);
   }
   /**
    * Test the DateField component.
    */
   public void testDate() {
      java.util.Date now = new java.util.Date();
      date.setDate(now);
      Form f = new Form("Today"s date");
      f.append(date);
      f.addCommand(backCommand);
      f.setCommandListener(this);
      display.setCurrent(f);
      currentMenu = "date";
   }
   /**
    * Test the Form component.
    */
   public void testForm() {
      form.append(gauge);
      form.append(textfield);
      form.addCommand(backCommand);
      form.setCommandListener(this);
      display.setCurrent(form);
      currentMenu = "form";
   }
   /**
    * Handle events.
    */  
   public void commandAction(Command c, Displayable d) {
      String label = c.getLabel();
      if (label.equals("Exit")) {
         destroyApp(true);
      } else if (label.equals("Back")) {
          if(currentMenu.equals("list") || currentMenu.equals("input") || 
               currentMenu.equals("date") || currentMenu.equals("form")) {
            // go back to menu
            mainMenu();
          } 
      } else {
         List down = (List)display.getCurrent();
         switch(down.getSelectedIndex()) {
           case 0: testTextBox();break;
           case 1: testList();break;
           case 2: testAlert();break;
           case 3: testDate();break;
           case 4: testForm();break;
         }
            
      }
  }
}





Hello TextBox MIDlet

/*
 * 
 * Copyright (c) 2000 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Author: Srikanth Raju
 *
 * This software is the confidential and proprietary information of Sun
 * Microsystems, Inc. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Sun.
 *
 * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
 * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
 * THIS SOFTWARE OR ITS DERIVATIVES.
 */
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
 * An example MIDlet with simple "Hello" text in a TextBox
 * Refer to the startApp, pauseApp, and destroyApp
 * methods so see how each handles the requested transition.
 */
public class HelloTextBoxMIDlet extends MIDlet
{
    private Display display;    // The display for this MIDlet
    public HelloTextBoxMIDlet() {
        display = Display.getDisplay(this);
    }
    /**
     * Start up the Hello MIDlet by creating the TextBox 
     */
    public void startApp() {
        TextBox t = new TextBox("Hello UCSC", "Hello Saturday!", 256, 0);
        display.setCurrent(t);
    }
    /**
     * Pause is a no-op since there are no background activities or
     * record stores that need to be closed.
     */
    public void pauseApp() {
    }
    /**
     * Destroy must cleanup everything not handled by the garbage collector.
     * In this case there is nothing to cleanup.
     */
    public void destroyApp(boolean unconditional) {
    }
}





Hide Text

//jad file (please verify the jar size)
/*
MIDlet-Name: HideText
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: HideText.jar
MIDlet-1: HideText, , HideText
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
public class HideText extends MIDlet implements CommandListener {
  private Display display;
  private Form form = new Form("Enter Password");
  private Command submit = new Command("Submit", Command.SCREEN, 1);
  private Command exit = new Command("Exit", Command.EXIT, 1);
  private TextField textfield = new TextField("Password:", "", 30, TextField.ANY
      | TextField.PASSWORD);
  public HideText() {
    display = Display.getDisplay(this);
    form.addCommand(exit);
    form.addCommand(submit);
    form.append(textfield);
    form.setCommandListener(this);
  }
  public void startApp() {
    display.setCurrent(form);
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }
  public void commandAction(Command command, Displayable displayable) {
    if (command == submit) {
      textfield.setConstraints(TextField.ANY);
      textfield.setString("Thank you.");
      form.removeCommand(submit);
    } else if (command == exit) {
      destroyApp(false);
      notifyDestroyed();
    }
  }
}





Login Midlet

/*
Learning Wireless Java
Help for New J2ME Developers
By Qusay Mahmoud
ISBN: 0-596-00243-2
*/
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;
public class LoginMidlet extends MIDlet implements CommandListener {
   private Display display;
   private TextField userName;
   private TextField password;
   private Form form;
   private Command cancel;
   private Command login;
   public LoginMidlet() {
      userName = new TextField("LoginID:", "", 10, TextField.ANY);
      password = new TextField("Password:", "", 10, TextField.PASSWORD);
      form = new Form("Sign in");
      cancel = new Command("Cancel", Command.CANCEL, 2);
      login = new Command("Login", Command.OK, 2);
   }
   public void startApp() {
      display = Display.getDisplay(this);
      form.append(userName);
      form.append(password);
      form.addCommand(cancel);
      form.addCommand(login);
      form.setCommandListener(this);
      display.setCurrent(form);
   }
   public void pauseApp() {
   }
   public void destroyApp(boolean unconditional) {
      notifyDestroyed();
   }
   public void validateUser(String name, String password) {
     if (name.equals("qm") && password.equals("j2")) {
       menu();
     } else {
       tryAgain();
     }
   }     
   public void menu() {
     List services = new List("Choose one", Choice.EXCLUSIVE);
     services.append("Check Mail", null);
     services.append("Compose", null);
     services.append("Addresses", null);
     services.append("Options", null);
     services.append("Sign Out", null);
     display.setCurrent(services);
   }
   public void tryAgain() {
     Alert error = new Alert("Login Incorrect", "Please try again", null, AlertType.ERROR);
     error.setTimeout(Alert.FOREVER);
     userName.setString("");
     password.setString("");
     display.setCurrent(error, form);
   }
   public void commandAction(Command c, Displayable d) {
      String label = c.getLabel();
      if(label.equals("Cancel")) {
        destroyApp(true);
      } else if(label.equals("Login")) {
         validateUser(userName.getString(), password.getString());
      }
   }
}





Phone Book

/*
 * PhoneBook.java 
 * Copyright (c) 2000 Sun Microsystems, Inc. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of Sun
 * Microsystems, Inc. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Sun.
 *
 * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
 * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
 * THIS SOFTWARE OR ITS DERIVATIVES.
 */
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
/**
 */
public class PhoneBook extends MIDlet implements CommandListener {
  private Command exitCommand; // The exit command
  private Command nextCommand;
  private Command newCommand;
  private TextBox t1;
  private TextBox t;
  private Display display; // The display for this MIDlet
  private String _name;
  private String _number;
  public PhoneBook() {
    display = Display.getDisplay(this);
    nextCommand = new Command("Next", Command.SCREEN, 2);
    exitCommand = new Command("Exit", Command.SCREEN, 2);
    newCommand = new Command("NewNumber", Command.SCREEN, 2);
  }
  public void startApp() {
    t = new TextBox("Name", "", 256, TextField.ANY);
    t.addCommand(nextCommand);
    t.setCommandListener(this);
    t1 = new TextBox("Number", "", 256, TextField.PHONENUMBER);
    t1.addCommand(newCommand);
    t1.addCommand(exitCommand);
    t1.setCommandListener(this);
    display.setCurrent(t);
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }
  public void commandAction(Command c, Displayable s) {
    if (c == exitCommand) {
      _name = t.getString();
      _number = t1.getString();
      System.out.println("Name = " + t.getString() + ", Number = "
          + t1.getString());
      destroyApp(false);
      notifyDestroyed();
    }
    if (c == nextCommand) {
      t1.setString(" ");
      display.setCurrent(t1);
    }
    if (c == newCommand) {
      display.setCurrent(t);
      _name = t.getString();
      _number = t1.getString();
      System.out.println("Name = " + t.getString() + ", Number = "
          + t1.getString());
      t.setString(" ");
    }
  }
}





Simple ClipBoard

/*--------------------------------------------------
* SimpleClipBoard.java
*
* Example from the book:     Core J2ME Technology
* Copyright John W. Muchow   http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class SimpleClipBoard extends MIDlet implements CommandListener
{
  private Display display;      // Reference to Display object
  private TextBox tbClip;      // Main textbox
  private Command cmExit;      // Command to exit
  private Command cmStartMark; // Command to start marking a block
  private Command cmCopy;      // Command to copy to clipboard 
  private Command cmPaste;     // Command to paste into textbox
  private int beginOffset = 0;  // The start index of copy
  private char[] clipBoard = null; // The clipboard
  private int clipBoardChars = 0;  // Number of chars in clipboard
  
  public SimpleClipBoard()
  {
    display = Display.getDisplay(this);
    // Create the Commands. Notice the priorities assigned
    cmExit = new Command("Exit", Command.EXIT, 1);
    cmStartMark = new Command("Mark", Command.SCREEN, 2);
    cmCopy = new Command("Copy", Command.SCREEN, 3);
    cmPaste = new Command("Paste", Command.SCREEN, 4);
    tbClip = new TextBox("Clip Board", "Tee to grn", 15, TextField.ANY);
    tbClip.addCommand(cmExit);
    tbClip.addCommand(cmStartMark);
    tbClip.addCommand(cmCopy);
    tbClip.addCommand(cmPaste);    
    tbClip.setCommandListener(this);
    
    // Allocate a clipboard big enough to hold the entire textbox
    clipBoard = new char[tbClip.getMaxSize()];
  }
      
  public void startApp() 
  {
    display.setCurrent(tbClip);
  }
  
  public void pauseApp()
  {
  }
     
  public void destroyApp(boolean unconditional)
  {
  }
  public void commandAction(Command c, Displayable s)
  {
    if (c == cmStartMark)
    {
      beginOffset = tbClip.getCaretPosition();
    }
    else if (c == cmCopy && (tbClip.getCaretPosition() > beginOffset))
    {
      // Allocate an array to hold the current textbox contents
      char[] chr = new char[tbClip.size()];
      
      // Get the current textbox contents
      tbClip.getChars(chr);
      // The count of characters in the clipboard      
      clipBoardChars = tbClip.getCaretPosition() - beginOffset;
      
      // Copy the text into the clipboard
      // arraycopy(source, sourceindex, dest, destindex, count)      
      System.arraycopy(chr, beginOffset, clipBoard, 0, clipBoardChars);
    }
    else if (c == cmPaste)
    {
      // Make sure the paste will not overrun the textbox length.
      if ((tbClip.size() + clipBoardChars) <= tbClip.getMaxSize())
        tbClip.insert(clipBoard, 0, clipBoardChars, tbClip.getCaretPosition());
    }
    else if (c == cmExit)
    {
      destroyApp(false);
      notifyDestroyed();
    } 
  }
}





TextBox Capture

/*
J2ME: The Complete Reference
James Keogh
Publisher: McGraw-Hill
ISBN 0072227109
*/
//jad file (please verify the jar size)
/*
MIDlet-Name: TextBoxCapture
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: TextBoxCapture.jar
MIDlet-1: TextBoxCapture, , TextBoxCapture
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class TextBoxCapture extends MIDlet implements CommandListener
{
  private Display display; 
  private TextBox textbox; 
  private Command submit; 
  private Command exit; 
  public TextBoxCapture()
  {
   display = Display.getDisplay(this);
   submit = new Command("Submit", Command.SCREEN, 1);
   exit = new Command("Exit", Command.EXIT, 1);
   textbox = new TextBox("First Name:", "", 30, TextField.ANY);
   textbox.addCommand(exit);
   textbox.addCommand(submit);    
   textbox.setCommandListener(this);   
  }
  public void startApp()
  {
   display.setCurrent(textbox);
  }
  public void pauseApp()
  { 
  }
  public void destroyApp(boolean unconditional)
  { 
  }
  public void commandAction(Command command, Displayable displayable)
  {
   if (command == submit)
   {
     textbox.setString("Hello, " + textbox.getString());
     textbox.removeCommand(submit);
   }
   else if (command == exit)
   {
      destroyApp(false);
      notifyDestroyed();
   }
  }
}





TextBox MIDlet

/*
J2ME in a Nutshell
By Kim Topley
ISBN: 0-596-00253-X
*/
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.lcdui.Ticker;
import javax.microedition.midlet.MIDlet;
public class TextBoxMIDlet extends MIDlet {
    // Maximum size of the text in the TextBox
    private static final int MAX_TEXT_SIZE = 64;
    
    // The TextBox
    protected TextBox textBox;
    
    // The MIDlet"s Display object
    protected Display display;
    
    // Flag indicating first call of startApp
    protected boolean started;
    
    protected void startApp() {
        if (!started) {
            // First time through - initialize            
            // Get the text to be displayed
            String str = null;
            try {
                InputStream is = getClass().getResourceAsStream("test.txt");
                InputStreamReader r = new InputStreamReader(is);
                char[] buffer = new char[32];
                StringBuffer sb = new StringBuffer();
                int count;
                while ((count = r.read(buffer, 0, buffer.length)) > -1) {
                    sb.append(buffer, 0, count);
                }
                str = sb.toString();
            } catch (IOException ex) {
                str = "Failed to load text";
            }
            
            // Create the TextBox
            textBox = new TextBox("TextBox Example", str, 
                                MAX_TEXT_SIZE, TextField.ANY);
            
            // Create a ticker and install it
            Ticker ticker = new Ticker("This is a ticker...");
            textBox.setTicker(ticker);
            
            // Install the TextBox as the current screen
            display = Display.getDisplay(this);            
            display.setCurrent(textBox);
            started = true;
        }        
    }
    protected void pauseApp() {
    }
    protected void destroyApp(boolean unconditional) {
    }
}





TextBox MIDlet 2

/*
J2ME in a Nutshell
By Kim Topley
ISBN: 0-596-00253-X
*/
import java.io.*;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
public class TextBox2MIDlet extends TextBoxMIDlet implements CommandListener {
    // Exit command
    private static final Command EXIT_COMMAND = 
                        new Command("Exit", Command.EXIT, 0);
    
    // OK command
    private static final Command OK_COMMAND =
                        new Command("OK", Command.OK, 0);
    
    // Clear text box content
    private static final Command CLEAR_COMMAND =
                        new Command("Clear", Command.SCREEN, 1);
    
    // Reverse the content of the text box
    private static final Command REVERSE_COMMAND =
                        new Command("Reverse", Command.SCREEN, 1);
    protected void startApp() {
        boolean firstTime = !started;
        super.startApp();
        
        // If this is the first execution
        // of startApp, install commands
        if (firstTime) {
            textBox.addCommand(OK_COMMAND);            
            textBox.addCommand(EXIT_COMMAND);
            textBox.addCommand(CLEAR_COMMAND);            
            textBox.addCommand(REVERSE_COMMAND);            
            textBox.setCommandListener(this);
        }
    }
    
    // Command implementations.
    public void commandAction(Command c, Displayable d) {
        if (c == EXIT_COMMAND) {
            destroyApp(true);
            notifyDestroyed();
        } else if (c == OK_COMMAND) {
            System.out.println("OK pressed");
        } else if (c == CLEAR_COMMAND) {
            textBox.setString(null);
        } else if (c == REVERSE_COMMAND) {
            String str = textBox.getString();
            if (str != null) {
                StringBuffer sb = new StringBuffer(str);
                textBox.setString(sb.reverse().toString());
            }            
        }
    }    
}
class TextBoxMIDlet extends MIDlet {
    // Maximum size of the text in the TextBox
    private static final int MAX_TEXT_SIZE = 64;
    
    // The TextBox
    protected TextBox textBox;
    
    // The MIDlet"s Display object
    protected Display display;
    
    // Flag indicating first call of startApp
    protected boolean started;
    
    protected void startApp() {
        if (!started) {
            // First time through - initialize            
            // Get the text to be displayed
            String str = null;
            try {
                InputStream is = getClass().getResourceAsStream("test.txt");
                InputStreamReader r = new InputStreamReader(is);
                char[] buffer = new char[32];
                StringBuffer sb = new StringBuffer();
                int count;
                while ((count = r.read(buffer, 0, buffer.length)) > -1) {
                    sb.append(buffer, 0, count);
                }
                str = sb.toString();
            } catch (IOException ex) {
                str = "Failed to load text";
            }
            
            // Create the TextBox
            textBox = new TextBox("TextBox Example", str, 
                                MAX_TEXT_SIZE, TextField.ANY);
            
            // Create a ticker and install it
            Ticker ticker = new Ticker("This is a ticker...");
            textBox.setTicker(ticker);
            
            // Install the TextBox as the current screen
            display = Display.getDisplay(this);            
            display.setCurrent(textBox);
            started = true;
        }        
    }
    protected void pauseApp() {
    }
    protected void destroyApp(boolean unconditional) {
    }
}





TextBox Shared ClipBoard

/*--------------------------------------------------
* SharedClipBoard.java
*
* A List component that can show one of two
* textboxes. Each textbox shares a common clipboard
*
* Example from the book:     Core J2ME Technology
* Copyright John W. Muchow   http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class SharedClipBoard extends MIDlet implements CommandListener
{
  private Display display;    // Reference to Display object
  private List lsMain;       // Main list
  private TextBoxCB tbClip1; // Textbox with clipboard  
  private TextBoxCB tbClip2; // Textbox with clipboard  
  private Command cmExit;    // Command to exit
  
  public SharedClipBoard()
  {
    display = Display.getDisplay(this);
    // Create list
    lsMain = new List("ClipBoard Testing", List.IMPLICIT); 
    lsMain.append("TextBox1", null);
    lsMain.append("TextBox2", null);
    
    // Create the exit command, add to list
    cmExit = new Command("Exit", Command.EXIT, 1);
    lsMain.addCommand(cmExit);
    lsMain.setCommandListener(this);
    
    // Allocate textboxes     
    tbClip1 = new TextBoxCB("TextBox1", "Email Address:  john@corej2me.ru", 50, TextField.ANY, this);
    tbClip2 = new TextBoxCB("TextBox2", "Web Address:  www.", 50, TextField.ANY, this);
  }
      
  public void startApp() 
  {
    showList();
  }
  
  public void pauseApp()
  {
  }
     
  public void destroyApp(boolean unconditional)
  {
  }
  public void showList()
  {
    // Display the list component
    display.setCurrent(lsMain);
  }
  
  public void commandAction(Command c, Displayable s)
  {
    // If an implicit list generated the event
    if (c == List.SELECT_COMMAND)
    {
      switch (lsMain.getSelectedIndex())
      {
        case 0:
          // Display textbox 1
          display.setCurrent(tbClip1);
          break;
  
        case 1:
          // Display textbox 2        
          display.setCurrent(tbClip2);
          break;
      }
    }
    else if (c == cmExit)
    {
      destroyApp(false);
      notifyDestroyed();
    } 
  }
}
/*--------------------------------------------------
* TextBoxCB.java
* 
* A textbox that includes a clipboard. This class
* encapsulates all the commands necessary to show
* a menu for mark, copy, cut and paste.
*
* Example from the book:     Core J2ME Technology
* Copyright John W. Muchow   http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
class TextBoxCB extends TextBox implements CommandListener
{
  private ClipBoard clipboard;  // The clipboard class
  private Command cmBack;      // Command to go back
  private Command cmStartMark; // Command to start marking a block
  
  private Command cmCopy;      // Command to copy to clipboard
  
  private Command cmCut;       // Command to cut to clipboard 
  
  private Command cmPaste;     // Command to paste into textbox
  private SharedClipBoard midlet; // The midlet
  
  public TextBoxCB(String title, String text, int maxSize, int constraints, 
                   SharedClipBoard midlet)
  {
    // Call the TextBox constructor
    super(title, text, maxSize, constraints);
    
    // Save reference to MIDlet so we can access its methods
    this.midlet =  midlet;
   
    // Create the Commands. Notice the priorities assigned
    cmBack = new Command("Back", Command.BACK, 1);
    cmStartMark = new Command("Mark", Command.SCREEN, 2);
    cmCopy = new Command("Copy", Command.SCREEN, 3);
    cmCut = new Command("Cut",  Command.SCREEN, 4);
    cmPaste = new Command("Paste", Command.SCREEN, 5);
    
    this.addCommand(cmBack);
    this.addCommand(cmStartMark);
    this.addCommand(cmCopy);
    this.addCommand(cmCut);
    this.addCommand(cmPaste);    
    this.setCommandListener(this);
    // Create a clipboard
    clipboard = new ClipBoard(this);
  }
  
  public void commandAction(Command c, Displayable s)
  {
    if (c == cmStartMark)
    {
      // Start to mark a block of text
      clipboard.startMark();  
    }
    else if (c == cmCopy)
    {
      // Copy text to clipboard
      clipboard.copy();
    }
    else if (c == cmCut)
    {
      // Cut text to clipboard
      clipboard.cut();                  
    }
    else if (c == cmPaste)
    { 
      // Paste from clipboard to textbox
      clipboard.paste();
    }
    else if (c == cmBack)
    {
      // Return to the list component
      midlet.showList();
    }
  }
}
/*--------------------------------------------------
* ClipBoard.java
*
* Core clipboard code -  mark, copy, cut and paste
*
* Example from the book:     Core J2ME Technology
* Copyright John W. Muchow   http://www.CoreJ2ME.ru
* You may use/modify for any non-commercial purpose
*-------------------------------------------------*/
class ClipBoard
{
  //--------------------------------------------------
  // Allocate clipboard. Note, both clipboard & count
  // of characters are shared across all instances
  //--------------------------------------------------
  private static char[] _clipBoard = new char[1000];
  private static int _clipBoardCount = 0;
  
  private int beginOffset = 0;  // The start index of copy
  private TextBox tb = null;   // textbox for this instance
  /*--------------------------------------------------
  * Hold reference to textbox that created clipboard
  *-------------------------------------------------*/  
  public ClipBoard(TextBox textbox)
  {
    tb = textbox;
  }
  /*--------------------------------------------------
  * Set starting point of copy
  *-------------------------------------------------*/  
  public void startMark()
  {
    beginOffset = tb.getCaretPosition();
  }
  /*--------------------------------------------------
  * Copy text into the clipboard
  *-------------------------------------------------*/  
  public void copy()
  {
    copy2clipboard();
  }
  /*--------------------------------------------------
  * Copy text into the clipboard. If successful copy,
  * delete text from the textbox.
  *-------------------------------------------------*/  
  public void cut()
  {
    if (copy2clipboard())
      tb.delete(beginOffset, tb.getCaretPosition() - beginOffset);
  }
  /*--------------------------------------------------
  * Do the actual copy into the clipboard
  *-------------------------------------------------*/
  private boolean copy2clipboard()
  {
    // Can only mark (copy/cut) going forward
    if (tb.getCaretPosition() > beginOffset)
    {
      // Allocate an array to hold the current textbox contents
      char[] chr = new char[tb.size()];
      
      // Get the current textbox contents
      tb.getChars(chr);
      // The count of characters in the clipboard      
      _clipBoardCount = tb.getCaretPosition() - beginOffset;
      
      // Copy the text into the clipboard
      // arraycopy(source, sourceindex, dest, destindex, count)
      System.arraycopy(chr, beginOffset, _clipBoard, 0, _clipBoardCount);
      return true;
    }
    else
      return false;    
  }
    
  /*--------------------------------------------------
  * Paste text from clipboard into the textbox 
  *-------------------------------------------------*/  
  public void paste()
  {
    // Make sure the paste will not overrun the textbox length
    if ((tb.size() + _clipBoardCount) <= tb.getMaxSize())
      tb.insert(_clipBoard, 0, _clipBoardCount, tb.getCaretPosition());
  }
}





TextField Capture

//jad file (please verify the jar size)
/*
MIDlet-Name: TextFieldCapture
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: TextFieldCapture.jar
MIDlet-1: TextFieldCapture, , TextFieldCapture
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
public class TextFieldCapture extends MIDlet implements CommandListener {
  private Display display;
  private Form form = new Form("Sign In Please");
  private Command submit = new Command("Submit", Command.SCREEN, 1);
  private Command exit = new Command("Exit", Command.EXIT, 1);
  private TextField textfield = new TextField("First Name:", "", 30, TextField.ANY);
  public TextFieldCapture() {
    display = Display.getDisplay(this);
    form.addCommand(exit);
    form.addCommand(submit);
    form.append(textfield);
    form.setCommandListener(this);
  }
  public void startApp() {
    display.setCurrent(form);
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }
  public void commandAction(Command command, Displayable displayable) {
    if (command == submit) {
      textfield.setString("Hello, " + textfield.getString());
      form.removeCommand(submit);
    } else if (command == exit) {
      destroyApp(false);
      notifyDestroyed();
    }
  }
}