gpt4 book ai didi

java - Graphics2D.drawString 中的换行符问题

转载 作者:太空宇宙 更新时间:2023-11-04 14:03:21 24 4
gpt4 key购买 nike

g2Graphics2D 类的实例。我希望能够绘制多行文本,但这需要换行符。以下代码在一行中呈现。

String newline = System.getProperty("line.separator");
g2.drawString("part1\r\n" + newline + "part2", x, y);

最佳答案

drawString 方法不处理换行符。

您必须自己将字符串拆分为换行符,并以适当的垂直偏移量一根一根地绘制线条:

void drawString(Graphics g, String text, int x, int y) {
for (String line : text.split("\n"))
g.drawString(line, x, y += g.getFontMetrics().getHeight());
}
<小时/>

这是一个完整的示例,可以让您了解这个想法:

import java.awt.*;

public class TestComponent extends JPanel {

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

public void paintComponent(Graphics g) {
super.paintComponent(g);
drawString(g, "hello\nworld", 20, 20);
g.setFont(g.getFont().deriveFont(20f));
drawString(g, "part1\npart2", 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);
}
}

给出以下结果:

enter image description here

关于java - Graphics2D.drawString 中的换行符问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29103420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com