Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

java - Problems with newline in Graphics2D.drawString

g2 is an instance of the class Graphics2D. I'd like to be able to draw multi-line text, but that requires a newline character. The following code renders in one line.

String newline = System.getProperty("line.separator");
g2.drawString("part1
" + newline + "part2", x, y);
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The drawString method does not handle new-lines.

You'll have to split the string on new-line characters yourself and draw the lines one by one with a proper vertical offset:

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

Here is a complete example to give you the idea:

import java.awt.*;

public class TestComponent extends JPanel {

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

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        drawString(g, "hello
world", 20, 20);
        g.setFont(g.getFont().deriveFont(20f));
        drawString(g, "part1
part2", 120, 120);
    }

    public static void main(String s[]) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new TestComponent());
        f.setSize(220, 220);
        f.setVisible(true);
    }
}

which gives the following result:

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...