Text Example in J2ME

In J2ME programming language canvas class is used to paint and draw the diagrams. Using the same canvas class we are going to draw a box around the text in our show text MIDlet Example.

Text Example in J2ME

Text Example in J2ME

     

In J2ME programming language canvas class is used to paint and draw the diagrams. Using the same canvas class we are going to draw a box around the text in our show text MIDlet Example. We have created a class called CanvasBoxText that extends the predefined canvas class to draw the box. In the code we have used different methods to get the values, these are..

  • int width = getWidth();   
  • int height = getHeight();  
  • g.setColor(255, 0, 0);   
  • g.fillRect(0, 0, width, height);   
  • g.setColor(0, 0, 255);  
  • String sandeep = "SANDEEP";   
  • int w = font.stringWidth(sandeep);   
  • int h = font.getHeight();   
  • int x = (width - w) / 2;   
  • int y = height / 2;  
  • g.setFont(font);   
  • g.drawString(sandeep, x, y, Graphics.TOP | Graphics.LEFT);   
  • g.drawRect(x, y, w, h);

After running the example you will get the output as given below..

In the output you can easily find out the text "SANDEEP" that is been displayed in the box. As I mentioned earlier, we need a canvas class to draw such kind of graphics in the J2ME application.

J2ME Source Code "BoxTextCanvas.java"

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

public class BoxTextCanvas extends MIDlet{
  private Display display;

  public void startApp(){
  Canvas canvas = new CanvasBoxText();
  display = Display.getDisplay(this);
  display.setCurrent(canvas);
  }

  public void pauseApp(){}

  public void destroyApp(boolean unconditional){}
}

class CanvasBoxText extends Canvas{
  private Font font;

  public CanvasBoxText(){
  font = Font.getFont(Font.FACE_PROPORTIONAL, 
  Font.STYLE_PLAIN, Font.SIZE_LARGE);

  }

  public void paint(Graphics g){
  int width = getWidth();
  int height = getHeight();

  g.setColor(25500);
  g.fillRect(00, width, height);
  g.setColor(00255);

  String sandeep = "SANDEEP";
  int w = font.stringWidth(sandeep);
  int h = font.getHeight();
  int x = (width - w) / 2;
  int y = height / 2;

  g.setFont(font);
  g.drawString(sandeep, x, y, Graphics.TOP | Graphics.LEFT);
  g.drawRect(x, y, w, h);
  }
}

Download Source Code