Get width and height : Font « J2ME « Java Tutorial






Get width and height
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 FontDimensionMIDlet extends MIDlet implements CommandListener {

  private Command exitCommand= new Command("Exit", Command.EXIT, 1);

  Display display;

  public void startApp() {
    Display display = Display.getDisplay(this);
    Displayable d = new FontDimensionCanvas();

    d.addCommand(exitCommand);
    d.setCommandListener(this);

    display.setCurrent(d);
  }

  public void pauseApp() {
  }

  public void destroyApp(boolean unconditional) {
  }

  public void commandAction(Command c, Displayable s) {
    notifyDestroyed();
  }
}

class FontDimensionCanvas extends Canvas {
  int width;

  int height;

  private Font aFont;

  public FontDimensionCanvas() {
    aFont = Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_PLAIN, Font.SIZE_LARGE);
  }

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

    String s = "TEXT";
    int stringWidth = aFont.stringWidth(s);
    int stringHeight = aFont.getHeight();

    g.setGrayScale(255);
    g.fillRect(0, 0, width - 1, height - 1);
    g.setGrayScale(0);
    g.drawRect(0, 0, width - 1, height - 1);

    g.setFont(aFont);
    g.drawString(s, 10, 10, Graphics.TOP | Graphics.LEFT);
    g.drawRect(10, 10, stringWidth, stringHeight);
  }
}








31.30.Font
31.30.1.Get font widthGet font width
31.30.2.Font styleFont style
31.30.3.System FontSystem Font
31.30.4.Medium Sized fontMedium Sized font
31.30.5.Bold Style FontBold Style Font
31.30.6.Italic Style FontItalic Style Font
31.30.7.Underlined Style FontUnderlined Style Font
31.30.8.Get width and heightGet width and height