0

I'm trying to make a method which will split a long text into lines and draw them on documents using Graphics. I managed to figure out how to split the lines that I get from a JTextArea component but don't know how to make them wrap/break when a line gets too long.

Here's my code so far:

    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());
    }

Any help is appreciated.

Edit:

My thoughts on a fix about this is to calculate the char position of the string and if it reaches a selected position then I add a line break ("\n") there. Any other suggestions or should I go for this one?

İsmail Y.
  • 3,579
  • 5
  • 21
  • 29
Ssiro
  • 127
  • 1
  • 5
  • 18

1 Answers1

1

You can use a word count method like this instead of the split method:

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"); 
}
clic
  • 365
  • 1
  • 13
  • There is no need to wrap `code` section in quote section, unless it is really quotation in which case you should also include its source in your answer. – Pshemo Feb 01 '17 at 20:29
  • Also `.append(word + " ")` is sign that someone doesn't understand purpose of StringBuilder. It is used to avoid string concatenation which creates its own new StringBuilder which means that this code is same as `.append(new StringBuilder(word).append(" ").toString())`. We should use `append(word).append(" ")` instead. – Pshemo Feb 01 '17 at 20:32