在做項目標時候,碰到屏幕分行顯示文字的標題,參考了部分材料之後,寫了如下解決計劃(沒有考慮英文單詞避免換行的標題):
public void paint(Graphics g) { Font font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM); g.setColor(125, 125, 125); g.fillRect(0, getHeight() / 2, getWidth(), getHeight()); g.setFont(font); g.setColor(0, 0, 0); Vector vc = MulString("屏幕分行顯示解決方法!屏幕分行顯示解決方法!屏幕分行顯示解決方法!"); for (int i = 0; i < vc.size(); i++) { g.drawString(vc.elementAt(i).toString(), 0, (getHeight() / 2 + getHeight() / 4 + font.getHeight() * i), 0); }} protected Vector MulString (String string) { Vector vc = new Vector(); Font font = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM); int width = 0; //記錄當前寬度,假如大於屏幕寬度,就添加到Vector int iPre = 0; //添加到Vector中字符串在原字符串中的起始位 int iNum = 0; //原字符串的總長度 for (int i = 0; i < string.length(); i++) { iNum++; width += font.charWidth(string.charAt(i)); if (width >= (getWidth() - 2)) { vc.addElement(string.substring(iPre, i)); iPre = i; width = 0; } } vc.addElement(string.substring(iPre, iNum)); return vc;}