javastringprintinggraphics2ddrawstring

Java split a string into multiple ones at a selected position


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?


Solution

  • 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"); 
    }