Print string with line breaks

667 views Asked by At

I'm working on a text editor and my next goal is to print the written text on a printer (not sysout).

I tried it many times and it worked but the line breaks got ignored.

Graphics pg = prjob.getGraphics();
            pg.setFont(textFont);
            pg.drawString(window.getText(), iPosX, iPosY);
            pg.dispose();

I created a new graphics and set the font. Then I took the text which was written into my editor window. iPosX & iPosY are the measurement of the paper.

How can I print the whole String considering the line breaks?

1

There are 1 answers

0
Turbut Alin On BEST ANSWER

Apparently, drawString() method does not handle line breaks. You can solve this by splitting the String on line breaks and printing each line separately on a new line. You can create a custom method to use like this one:

private void drawString(Graphics g, String text, int x, int y) {
    String[] splittedText = text.split("\n");
    for (int i = 0; i < splittedText.length; i++) {
        String line = splittedText[i];
        g.drawString(line, x, y + (g.getFontMetrics().getHeight() * i));
    }
}

Hope it helps!