Java/J2ME/Alert

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

An example MIDlet with simple Alert UI component containing an Image.

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
 * An example MIDlet with simple "Alert" UI component containing an Image.
 */
public class AlertImage extends MIDlet
{
    private Display display;    // The display for this MIDlet
   private Alert myAlert = null;
    public AlertImage() {
    }
    /**
     * Call showAlert
     */
    public void startApp() {
       display = Display.getDisplay(this);
     TextBox t = new TextBox("Hello MIDlet", "Hello J2MECamp!", 256, 0);
     display.setCurrent(t);
     System.out.println( "Gonna create Alert.." );
     createAlert();
   }

   /**
   * Puts up an Alert with an Image
   */
   private void createAlert() 
    {
     myAlert = new Alert("MIDlet Alert");
     String[] alertString = { " Alert String" };
     myAlert.setTimeout(Alert.FOREVER);
   
       // Add an image to Alert
       if (display.numColors() > 2) 
       {
          String icon = (display.isColor()) ?"/JavaPowered-8.png" : "/JavaPowered-2.png";
           try
           {
              Image image = Image.createImage( icon );
              if (image != null)
              {
                  myAlert.setImage(image);
                  System.out.println( "Image created and added to alert.. " );
              }
              else
              {
                 System.out.println( "No Image created... " );
              }
              // Add string to Alert
              for ( int i = 0; i < alertString.length; i++ ) {
                 myAlert.setString( alertString[i] );
              }
              
              if ( myAlert != null ) {
                display.setCurrent( myAlert );
              }
           }
           catch( Exception e )
           {
              System.out.println( "Exception in CreateImage() " );
           }
     }
    }
     
    /**
     * 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) {
    }
}





High-Level Display Screens : Alert

//jad file (please verify the jar size)
/*
MIDlet-Name: DisplayAlert
MIDlet-Version: 1.0
MIDlet-Vendor: MyCompany
MIDlet-Jar-URL: DisplayAlert.jar
MIDlet-1: DisplayAlert, , DisplayAlert
MicroEdition-Configuration: CLDC-1.0
MicroEdition-Profile: MIDP-1.0
MIDlet-JAR-SIZE: 100
*/
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
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.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class DisplayAlert extends MIDlet implements CommandListener {
  private Display display;
  private Alert alert;
  private Form form = new Form("Throw Exception");
  private Command exit = new Command("Exit", Command.SCREEN, 1);
  private boolean exitFlag = false;
  public DisplayAlert() {
    display = Display.getDisplay(this);
    form.addCommand(exit);
    form.setCommandListener(this);
  }
  public void startApp() {
    display.setCurrent(form);
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) throws MIDletStateChangeException {
    if (unconditional == false) {
      throw new MIDletStateChangeException();
    }
  }
  public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
      try {
        if (exitFlag == false) {
          alert = new Alert("Busy", "Please try again.", null, AlertType.WARNING);
          alert.setTimeout(Alert.FOREVER);
          display.setCurrent(alert, form);
          destroyApp(false);
        } else {
          destroyApp(true);
          notifyDestroyed();
        }
      } catch (Exception exception) {
        exitFlag = true;
      }
    }
  }
}





Modal Alert

/*--------------------------------------------------
* ModalAlert.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 ModalAlert extends MIDlet implements CommandListener
{
  private Display display;    // Reference to Display object
  private Form fmMain;       // Main form 
  private Alert alTest;      // Alert to show text and image
  private Command cmExit;    // Command to exit the MIDlet
 
  public ModalAlert()
  {
    display = Display.getDisplay(this);
    
    cmExit = new Command("Exit", Command.SCREEN, 1);
    fmMain = new Form("Welcome");
    fmMain.append("Text string inside the Form");
    fmMain.addCommand(cmExit);
    fmMain.setCommandListener(this);
  }
  public void startApp()
  {
    showAlert();
  }
  public void pauseApp()
  { 
  }
  public void destroyApp(boolean unconditional)
  {
  }
  public void showAlert()
  {
    try
    { 
      // Create an image
      Image im = Image.createImage("/coffee.png");
      // Create Alert, add text and image, associate a sound
      alTest = new Alert("New Alert", "Time for more Java", 
                          im, AlertType.INFO);
      // Set Alert to type Modal
      alTest.setTimeout(Alert.FOREVER);
    }    
    catch(Exception e)
    {
      System.out.println("Unable to read png image.");
    }
    
    // Display the Alert. Once dismissed, display the form
    display.setCurrent(alTest, fmMain);      
  }
  public void commandAction(Command c, Displayable s)
  {
    if (c == cmExit)
    {
      destroyApp(true);
      notifyDestroyed();
    }
  }
}





Multi Alert

/* License
 * 
 * Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *  
 *  * Redistribution of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 * 
 *  * Redistribution in binary form must reproduce the above copyright notice,
 *      this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of Sun Microsystems, Inc. or the names of contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *  
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *  
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility. 
 */
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import java.util.*;

public class MultiAlert extends MIDlet {
    Display      display;
    Command      exitCommand = new Command( "Exit", Command.EXIT,
                                                             1 );
    Timer        timer1 = new Timer();
    Timer        timer2 = new Timer();
    Timer        timer3 = new Timer();
    MainForm     form = new MainForm();
    AlertRouter  router;
    public MultiAlert() {
        display = Display.getDisplay( this );
        router = new AlertRouter( display );
        timer1.schedule( new AlertTrigger( "Alert 1",
                             "This is alert #1" ), 5000, 10000 );
        timer2.schedule( new AlertTrigger( "Alert 2",
                              "This is alert #2" ), 5000, 7000 );
        timer3.schedule( new AlertTrigger( "Alert 3",
                              "This is alert #3" ), 5000, 9000 );
    }
    protected void destroyApp( boolean unconditional ) {
        timer1.cancel();
        timer2.cancel();
        timer3.cancel();
    }
    protected void startApp() {
        display.setCurrent( form );
    }
    protected void pauseApp() {
    }
    public void exit(){
        destroyApp( true );
        notifyDestroyed();
    }
    class AlertTrigger extends TimerTask {
        public AlertTrigger( String title, String message )
        {
            this.title = title;
            this.message = message;
        }
          public void run(){
            Alert alert = new Alert( title, message, null, null );
            alert.setTimeout( Alert.FOREVER );
            router.showAlert( alert );
       }
        private String title;
        private String message;
    }
    class MainForm extends Form implements CommandListener {
        public MainForm(){
            super( "MultiAlert Demo" );
            addCommand( exitCommand );
            setCommandListener( this );
        }
        public void commandAction( Command c, Displayable d ){
            exit();
        }
    }
}





Two Alerts

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
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 TwoAlerts extends MIDlet implements CommandListener {
  private Display mDisplay;
  private TextBox mTextBox;
  private Alert mTimedAlert;
  private Alert mModalAlert;
  private Command aboutCommand, goCommand, exitCommand;
  public TwoAlerts() {
    aboutCommand = new Command("About", Command.SCREEN, 1);
    goCommand = new Command("Go", Command.SCREEN, 1);
    exitCommand = new Command("Exit", Command.EXIT, 2);
    mTextBox = new TextBox("TwoAlerts", "", 32, TextField.ANY);
    mTextBox.addCommand(aboutCommand);
    mTextBox.addCommand(goCommand);
    mTextBox.addCommand(exitCommand);
    mTextBox.setCommandListener(this);
    mTimedAlert = new Alert("Network error", "A network error occurred. Please try again.", null,
        AlertType.INFO);
    mModalAlert = new Alert("About TwoAlerts",
        "TwoAlerts is a simple MIDlet that demonstrates the use of Alerts.", null, AlertType.INFO);
    mModalAlert.setTimeout(Alert.FOREVER);
  }
  public void startApp() {
    mDisplay = Display.getDisplay(this);
    mDisplay.setCurrent(mTextBox);
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }
  public void commandAction(Command c, Displayable s) {
    if (c == aboutCommand)
      mDisplay.setCurrent(mModalAlert);
    else if (c == goCommand)
      mDisplay.setCurrent(mTimedAlert, mTextBox);
    else if (c == exitCommand)
      notifyDestroyed();
  }
}