User Define Alert Example

Creating a user defined alert message, In the given example we have created a image that can be fill with some colors and text.

User Define Alert Example

     

Creating a user defined alert message, In the given example we have created a image that can be fill with some colors and text. The following source code shows how to create the image, how to set the color and how to draw string. On clicking Alert option, a alert message will be displayed with image on the same screen.

im = Image.createImage(240220);
Graphics graphics = im.getGraphics();
Font font = Font.getFont(Font.FACE_SYSTEM, 
Font.STYLE_PLAIN, Font.SIZE_MEDIUM);

graphics.setFont(font);
graphics.setColor(196248192);
graphics.fillRoundRect(0,0, im.getWidth()-1
im.getHeight()-
12020); 
graphics.setColor(000); 
graphics.drawString(message, (im.getWidth()/2
- (font.stringWidth(message)/
2),
0, Graphics.TOP | Graphics.LEFT);

 

The Application is as follows:

 

 

 

Source Code of AlertExample.java

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class AlertExample extends MIDlet{
  private Display  display; 
  private ImageCanvas canvas;
  
  public AlertExample(){
  display = Display.getDisplay(this);
  canvas  = new ImageCanvas(this);
  }

  protected void startApp(){
  display.setCurrent( canvas );
  }

  protected void pauseApp(){ }

  protected void destroyApp(boolean unconditional){ }

  public void exitMIDlet(){
  destroyApp(true);
  notifyDestroyed();
  }
}

class ImageCanvas extends Canvas implements CommandListener{
  private Command cmExit;  
  private AlertExample midlet;
  private Image im = null;
  private String message = "This is alert message";
  
  public ImageCanvas(AlertExample midlet){
  this.midlet = midlet;

  cmExit = new Command("Exit", Command.EXIT, 1);
  addCommand(cmExit);
  setCommandListener(this);

  try{
  im = Image.createImage(240, 220);
  Graphics graphics = im.getGraphics();
  Font font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_MEDIUM);
  graphics.setFont(font);
  graphics.setColor(196, 248, 192);
  graphics.fillRoundRect(0,0, im.getWidth()-1, im.getHeight()-1, 20, 20); 
  graphics.setColor(0, 0, 0); 
  graphics.drawString(message, (im.getWidth()/2) - (font.stringWidth(message)/2),
 0, Graphics.TOP | Graphics.LEFT);
  }
  catch (Exception e){
  System.err.println("Error during image creation");
  }  
  } 
  
  protected void paint(Graphics g){
  if (im != null)
  g.drawImage(im, getWidth()/2, getHeight()/2, Graphics.VCENTER | Graphics.HCENTER);
  }

  public void commandAction(Command c, Displayable d){
  if (c == cmExit)
  midlet.exitMIDlet();
  }
} 

Download Source Code

Ads