Java/J2ME/Form

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

Change Label Text

/*--------------------------------------------------
* ChangeLabelText.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 ChangeLabelText extends MIDlet implements CommandListener
{
  private Display display;      // Reference to Display object
  private Form fmMain;          // The main form
  private StringItem siUser;    // The message
  private Command cmNext;       // Next label and message
  private Command cmExit;       // Command to exit the MIDlet
  public ChangeLabelText()
  {
    display = Display.getDisplay(this);
    // Create text message and commands
    siUser = new StringItem("UserId: ", "johnm");
    cmNext = new Command("Next", Command.SCREEN, 1);
    cmExit = new Command("Exit", Command.EXIT, 1);
    // Create Form, add Command & StringItem, listen for events
    fmMain = new Form("Preferences");    
    fmMain.addCommand(cmExit);
    fmMain.addCommand(cmNext);    
    fmMain.append(siUser);
    fmMain.setCommandListener(this);   
  }
  // Called by application manager to start the MIDlet.
  public void startApp()
  {
    display.setCurrent(fmMain);
  }
  public void pauseApp()
  { }
  
  public void destroyApp(boolean unconditional)
  { }
  public void commandAction(Command c, Displayable s)
  {
    if (c == cmNext)
    {
      // This method is inherited from the Item class
      siUser.setLabel("Account #: ");
      
      // Change the text
      siUser.setText("731");           
      
      // Remove the Next command
      fmMain.removeCommand(cmNext);
    }
    else if (c == cmExit)
    {
      destroyApp(false);
      notifyDestroyed();
    } 
  }
}





Create Form With Items

//jad file (please verify the jar size)
/*
MIDlet-Name: CreatingFormWithItems
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: CreatingFormWithItems.jar
MIDlet-1: CreatingFormWithItems, , CreatingFormWithItems
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.StringItem;
import javax.microedition.midlet.MIDlet;
public class CreatingFormWithItems extends MIDlet implements CommandListener {
  private Display display;
  private Form form;
  private Command exit = new Command("Exit", Command.SCREEN, 1);
  public CreatingFormWithItems() {
    display = Display.getDisplay(this);
    StringItem messages[] = new StringItem[] { new StringItem("Welcome, ", "glad you could come."),
        new StringItem("Hello, ", "Mary.") };
    form = new Form("Display Form with Items", messages);
    form.addCommand(exit);
    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 == exit) {
      destroyApp(true);
      notifyDestroyed();
    }
  }
}





Display Stats

/*--------------------------------------------------
* DisplayStats.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 DisplayStats extends MIDlet implements CommandListener
{
  private Display display;             // Reference to Display object
  private Form fmMain;                 // A Form 
  private Alert alTest;                // An Alert
  private Command cmExit;              // A Command to exit the MIDlet
 
  public DisplayStats()
  {
    display = Display.getDisplay(this);
    
    cmExit = new Command("Exit", Command.SCREEN, 1);
    fmMain = new Form("Welcome");
    fmMain.addCommand(cmExit);
    fmMain.setCommandListener(this);
    System.out.println("Display " + (display.isColor() ? "does" : "does not") + " support Color");
    System.out.println("Number of colors: " + display.numColors());
  }
  // Called by application manager to start the MIDlet.
  public void startApp()
  {
    alTest = new Alert("Alert", "This alert screen will be followed by the main form", null, null);
    alTest.setTimeout(Alert.FOREVER);
    display.setCurrent(alTest, fmMain);
  }
  // We are about to be placed in the Paused state
  public void pauseApp()
  {
  }
  // We are about to enter the Destroyed state
  public void destroyApp(boolean unconditional)
  {
  }
  // Check to see if the Exit command was selected
  public void commandAction(Command c, Displayable s)
  {
    if (c == cmExit)
    {
      destroyApp(true);
      notifyDestroyed();
    }
  }
}





Form Example MIDlet

/*
J2ME in a Nutshell
By Kim Topley
ISBN: 0-596-00253-X
*/
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
public class FormExampleMIDlet extends MIDlet {
    
    
    // The MIDlet"s Display object
    protected Display display;
    
    // Flag indicating first call of startApp
    protected boolean started;
    
    protected void startApp() {
        if (!started) {
            display = Display.getDisplay(this);
            
            Form form = new Form("Item Layout");
            
            form.append("Hello");
            form.append("World");
            
            form.append("\nLet"s start\na new line\n");
            form.append("This is quite a long string that may not fit on one line");
            
            form.append(new TextField("Name", "J. Doe", 32, TextField.ANY));
            form.append("Address");
            form.append(new TextField(null, null, 32, TextField.ANY));            
            
            display.setCurrent(form);
            
            started = true;
        }
    }
    protected void pauseApp() {
    }
    protected void destroyApp(boolean unconditional) {
    }
}





Form Juggle

/*--------------------------------------------------
* FormJuggle.java
*
* Show how a Form component handles inserting and
* setting (replacing) Items
*
* 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 FormJuggle extends MIDlet implements CommandListener
{
  private Display display;      // Reference to display object 
  private Form fmMain;          // The main form
  private Command cmInsert;     // Command to insert items
  private DateField dfDate;     // Display date
  private TextField tfSize;     // Product size
  private TextField tfQuantity; // Product quantity
  private int dateIndex;        // Index of dfDate 
  public FormJuggle()
  {
    display = Display.getDisplay(this);
    // Create the date and populate with current date
    dfDate = new DateField("", DateField.DATE);
    dfDate.setDate(new java.util.Date());
    // Define two textfields and two commands
    tfSize = new TextField("Size", "Large", 5, TextField.ANY); 
    tfQuantity = new TextField("Quantity:", "3", 2, TextField.NUMERIC); 
    cmInsert = new Command("Insert", Command.SCREEN, 1);
    // Create the form, add insert command
    fmMain = new Form("Form Stuff");
    fmMain.addCommand(cmInsert);
  
    // Append date to form & save index value where it was inserted
    dateIndex = fmMain.append(dfDate);
    // Capture events
    fmMain.setCommandListener(this);    
  }
  // Called by application manager to start the MIDlet.
  public void startApp()
  {
    display.setCurrent(fmMain);
  }
  public void pauseApp()
  { }
  
  public void destroyApp(boolean unconditional)
  { }
  public void commandAction(Command c, Displayable s)
  {
    if (c == cmInsert)
    {
      // One item on form, insert textfield prior to datefield
      if (fmMain.size() == 1)
      {
        fmMain.insert(dateIndex, tfQuantity);     
        dateIndex += 1;   // Date index has changed, update it
      }
      // If two items and last item is datefield, replace it
      else if (fmMain.size() == 2 && fmMain.get(1) == dfDate)
        fmMain.set(dateIndex, tfSize);
    }
  }
}





Form Scroll

/*--------------------------------------------------
* FormScroll.java
*
* Show how a Form component handles scrolling
* when multiple Items are on the display
*
* 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 FormScroll extends MIDlet implements CommandListener
{
  private Display display;      // Reference to display object 
  private Form frmMain;         // The main form
  private Command cmdExit;      // Command to exit
  private TextField txfSize;    // Product size
  private ChoiceGroup chgEmail; // Choice group
  private Gauge gauVolume;      // Volume
  public FormScroll()
  {
    display = Display.getDisplay(this);
    // Create TextField
    txfSize = new TextField("Size", "Large", 5, TextField.ANY); 
    
    // Create an exclusive (radio) choice group, and append entries
    chgEmail = new ChoiceGroup("Email Options", Choice.EXCLUSIVE);
    chgEmail.append("Read", null);
    chgEmail.append("Forward", null);    
    chgEmail.append("Delete", null);    
    // Create the gauge
    gauVolume = new Gauge("Sound Level", true, 30, 4);
    
    cmdExit = new Command("Exit", Command.EXIT, 1);
    // Create the form
    frmMain = new Form("Form Stuff");
    frmMain.append(txfSize);
    frmMain.append(chgEmail);
    frmMain.append(gauVolume);    
    frmMain.addCommand(cmdExit);
  
    // Capture events
    frmMain.setCommandListener(this);    
  }
  // Called by application manager to start the MIDlet.
  public void startApp()
  {
    display.setCurrent(frmMain);
  }
  public void pauseApp()
  { }
  
  public void destroyApp(boolean unconditional)
  { }
  public void commandAction(Command c, Displayable s)
  {
    if (c == cmdExit)
    {
      destroyApp(false);
      notifyDestroyed();
    }
  }
}





Read Display File

/*--------------------------------------------------
* ReadDisplayFile.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.*;
import java.io.*;
public class ReadDisplayFile extends MIDlet implements CommandListener
{
  private Display display;    // Reference to Display object
  private Form fmMain;       // Main form
  private Command cmHelp;    // Command to show a help file
  private Command cmExit;    // Command to exit the MIDlet
  private Alert alHelp;      // Alert to display help file text
  public ReadDisplayFile()
  {
    display = Display.getDisplay(this);
    
    cmHelp = new Command("Help", Command.SCREEN, 1);
    cmExit = new Command("Exit", Command.EXIT, 1);    
    
    fmMain = new Form("Read File");
    fmMain.addCommand(cmExit);
    fmMain.addCommand(cmHelp);
    fmMain.setCommandListener(this);
  }
  public void startApp()
  {
    display.setCurrent(fmMain);
  }
  public void pauseApp()
  { }
  public void destroyApp(boolean unconditional)
  { }
  public void commandAction(Command c, Displayable s)
  {
    if (c == cmHelp)
    {
      String str;
      // Access the resource and read its contents
      if ((str = readHelpText()) != null)
      {
        // Create an Alert to display the help text        
        alHelp = new Alert("Help", str, null, null);
        alHelp.setTimeout(Alert.FOREVER);
        display.setCurrent(alHelp, fmMain);
      }
    }
    else if (c == cmExit)
    {
      destroyApp(false);
      notifyDestroyed();
    } 
  }
  
  private String readHelpText()
  {
    InputStream is = getClass().getResourceAsStream("help.txt");
    try 
    {
      StringBuffer sb = new StringBuffer();
      int chr, i = 0;
      // Read until the end of the stream      
      while ((chr = is.read()) != -1)
          sb.append((char) chr);
      return sb.toString();
    }
    catch (Exception e)
    {         
      System.out.println("Unable to create stream");
    }
    return null;
  }
}





Verify Area Code

/*--------------------------------------------------
* VerifyAreaCode.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 VerifyAreaCode extends MIDlet implements CommandListener
{
  private Display display;      // Reference to Display object
  private Form fmMain;         // The main form
  private Command cmTest;      // Next label and message
  private Command cmExit;      // Command to exit the MIDlet
  private TextField tfPhone;   // Phone number
  private String areaCodeTable [][] = {
                                    {"512", "912"}, // Old area code, new area code
                                    {"717", "917"} };   
    
  public VerifyAreaCode()
  {
    display = Display.getDisplay(this);
    // Create commands
    cmTest = new Command("Test", Command.SCREEN, 1);
    cmExit = new Command("Exit", Command.EXIT, 1);
    // Textfield for phone number
    tfPhone = new TextField("Phone:", "", 10, TextField.PHONENUMBER);
    // Create Form, add Commands & textfield, listen for events
    fmMain = new Form("Area Codes");    
    fmMain.addCommand(cmExit);
    fmMain.addCommand(cmTest);    
    fmMain.append(tfPhone);
    fmMain.setCommandListener(this);   
  }
  // Called by application manager to start the MIDlet.
  public void startApp()
  {
    display.setCurrent(fmMain);
  }
  public void pauseApp()
  { }
  
  public void destroyApp(boolean unconditional)
  { }
  public void commandAction(Command c, Displayable s)
  {
    if (c == cmTest)
    {
      if (tfPhone.size() == 10)
      {
        char buffer[] = new char[10];
        // Get phone number into byte array         
        tfPhone.getChars(buffer);
        // Call method to check the area code table.
        // Create a new StringItem to display, 
        // passing in "null" as the StringItem
        StringItem tmp = new StringItem(null, ("The area code " + (areaCodeLookup(buffer) ? "has" : "has not") + " been updated."));
        
        // Place at the end of the form
        if (fmMain.size() == 1)  // Only tfPhone on form
          fmMain.append(tmp);
        else                      // Replace previous StringItem
          fmMain.set(1, tmp);
      }
    }
    else if (c == cmExit)
    {
      destroyApp(false);
      notifyDestroyed();
    } 
  }
  /*--------------------------------------------------
  * Compare the area code the user entered with the 
  * area code table. If a match is found, replace
  * the user"s code with the new code from the table
  *-------------------------------------------------*/  
  private boolean areaCodeLookup(char [] buffer)
  {
    // Get the area code (only) from the users entry
    String str = new String(buffer, 0, 3);
    
    for (int x = 0; x < areaCodeTable.length; x++)
    {
      // If we find a match in the table
      if (str.equals(areaCodeTable[x][0]))
      {
        // Delete the area code
        tfPhone.delete(0, 3);
        
        // Insert the new area code
        tfPhone.insert(areaCodeTable[x][1].toCharArray(), 0, 3, 0);
        return true;
      }
    }
    return false;
  }
}