2017-02-01 25 views
0

我試圖製作一種將長文本拆分爲多行並使用圖形在文檔上繪製它們的方法。我設法弄清楚如何拆分從JTextArea組件獲得的線條,但是當線條太長時不知道如何使它們換行/斷開。Java在選定的位置將字符串拆分爲多個字符

這裏是我到目前爲止的代碼:

void drawString(Graphics g, String text, int x, int y, Font w) { 
     g.setFont(w); 
     for (String line : text.split("\n")) 
      g.drawString(line, x, y += g.getFontMetrics().getHeight()); 
    } 

任何幫助表示讚賞。

謝謝。

編輯:

我上有關此修復程序的想法是計算字符串的炭位置,如果它到達選定的位置,那麼我添加了一個換行符(「\ n」)那裏。任何其他建議,或者我應該去這個嗎? 謝謝。

+1

你是什麼意思?當前的代碼適用於新的行,但不是當它們變得太長時。 – Ssiro

+0

我是誤讀,我會刪除評論。 – AntonH

回答

1

您可以使用這樣的,而不是分裂法字數統計方法:

public String[] splitIntoLine(String input, int maxCharInLine){ 

StringTokenizer tok = new StringTokenizer(input, " "); 
StringBuilder output = new StringBuilder(input.length()); 
int lineLen = 0; 
while (tok.hasMoreTokens()) { 
    String word = tok.nextToken(); 

    while(word.length() > maxCharInLine){ 
     output.append(word.substring(0, maxCharInLine-lineLen) + "\n"); 
     word = word.substring(maxCharInLine-lineLen); 
     lineLen = 0; 
    } 

    if (lineLen + word.length() > maxCharInLine) { 
     output.append("\n"); 
     lineLen = 0; 
    } 
    output.append(word).append(" "); 

    lineLen += word.length() + 1; 
} 
// output.split(); 
// return output.toString(); 
return output.toString().split("\n"); 
} 
+0

有沒有必要換'code'部分報價部分,除非是真正的報價在這種情況下,你還應該包括它在你的答案來源。 – Pshemo

+0

對不起,在我的智能手機上做過...... – clic

+0

另外'.append(word +「」)是有人不明白StringBuilder的目的的標誌。它是用來避免創建自己的新的StringBuilder字符串連接,這意味着這個代碼是一樣的'.append(新的StringBuilder(字).append(」「)的ToString())'。我們應該使用'append(word).append(「」)'來代替。 – Pshemo

相關問題