fontcanvas.java

来自「j2me的程序」· Java 代码 · 共 79 行

JAVA
79
字号
import javax.microedition.lcdui.*;

public class FontCanvas
    extends Canvas
    implements CommandListener {

  private Font systemFont;
  private Font monospaceFont;
  private Font proportionalFont;

  private Command boldCommand;
  private Command italicCommand;
  private Command underlineCommand;

  FontCanvas() {
    this(Font.STYLE_PLAIN);
  }

  FontCanvas(int style) {
    setStyle(style);
    boldCommand = new Command("粗体", Command.SCREEN, 1);
    italicCommand = new Command("斜体", Command.SCREEN, 1);
    underlineCommand = new Command("下划线", Command.SCREEN, 1);

    addCommand(boldCommand);
    addCommand(italicCommand);
    addCommand(underlineCommand);
    setCommandListener(this);
  }

  public void setStyle(int style) {
    systemFont = Font.getFont(Font.FACE_SYSTEM,
        style, Font.SIZE_MEDIUM);

    monospaceFont = Font.getFont(Font.FACE_MONOSPACE,
        style, Font.SIZE_MEDIUM);

    proportionalFont = Font.getFont(Font.FACE_PROPORTIONAL,
        style, Font.SIZE_MEDIUM);
  }

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

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

    int y = 10;

    y += showFont(g, "System", 0, y, systemFont);
    y += showFont(g, "Monospace", 0, y, monospaceFont);
    y += showFont(g, "Proportional", 0, y, proportionalFont);
  }

  private int showFont(Graphics g, String s, int x, int y, Font f) {
    g.setFont(f);
    g.drawString(s, x, y, Graphics.TOP | Graphics.LEFT);
    return f.getHeight();
  }

  public void commandAction(Command c, Displayable s) {
    boolean isBold = systemFont.isBold() ^ (c == boldCommand);
    boolean isItalic = systemFont.isItalic() ^ (c == italicCommand);
    boolean isUnderline = systemFont.isUnderlined() ^
        (c == underlineCommand);

    int style = (isBold ? Font.STYLE_BOLD : 0) |
                (isItalic ? Font.STYLE_ITALIC : 0) |
                (isUnderline ? Font.STYLE_UNDERLINED : 0);

    setStyle(style);
    repaint();
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?