Draw Rectangle and string : Draw String « J2ME « Java Tutorial






Draw Rectangle and string
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.midlet.MIDlet;

public class BoxTextMIDlet extends MIDlet {
  public void startApp() {
    Displayable d = new BoxTextCanvas();

    d.addCommand(new Command("Exit", Command.EXIT, 0));
    d.setCommandListener(new CommandListener() {
      public void commandAction(Command c, Displayable s) {
        notifyDestroyed();
      }
    });

    Display.getDisplay(this).setCurrent(d);
  }

  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
  }
}

class BoxTextCanvas extends Canvas {
  private Font mFont;

  public BoxTextCanvas() {
    mFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_PLAIN, Font.SIZE_LARGE);
  }

  public void paint(Graphics g) {
    int w = getWidth();
    int h = getHeight();

    g.setColor(0xffffff);
    g.fillRect(0, 0, w, h);
    g.setColor(0x000000);

    String s = "dolce";
    int stringWidth = mFont.stringWidth(s);
    int stringHeight = mFont.getHeight();
    int x = (w - stringWidth) / 2;
    int y = h / 2;

    g.setFont(mFont);
    g.drawString(s, x, y, Graphics.TOP | Graphics.LEFT);
    g.drawRect(x, y, stringWidth, stringHeight);
  }
}








31.28.Draw String
31.28.1.Draw stringDraw string
31.28.2.Draw string with font settingDraw string with font setting
31.28.3.Draw Rectangle and stringDraw Rectangle and string
31.28.4.Draw string on the top and leftDraw string on the top and left
31.28.5.Draw string to the top and rightDraw string to the top and right
31.28.6.Draw string to the bottom leftDraw string to the bottom left
31.28.7.Draw string to the bottom and rightDraw string to the bottom and right
31.28.8.Draw string to the base line and horizontal centerDraw string to the base line and horizontal center
31.28.9.change font and draw stringchange font and draw string