pki*_*sky 47 java string newline graphics2d
g2是类的一个实例Graphics2D.我希望能够绘制多行文本,但这需要换行符.以下代码在一行中呈现.
String newline = System.getProperty("line.separator");
g2.drawString("part1\r\n" + newline + "part2", x, y);
Run Code Online (Sandbox Code Playgroud)
aio*_*obe 82
该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());
}
Run Code Online (Sandbox Code Playgroud)
这是一个完整的例子来给你这个想法:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
得出以下结果:

小智 9
我只是通过给出线宽来自动绘制长文本分割的方法.
public static void drawStringMultiLine(Graphics2D g, String text, int lineWidth, int x, int y) {
FontMetrics m = g.getFontMetrics();
if(m.stringWidth(text) < lineWidth) {
g.drawString(text, x, y);
} else {
String[] words = text.split(" ");
String currentLine = words[0];
for(int i = 1; i < words.length; i++) {
if(m.stringWidth(currentLine+words[i]) < lineWidth) {
currentLine += " "+words[i];
} else {
g.drawString(currentLine, x, y);
y += m.getHeight();
currentLine = words[i];
}
}
if(currentLine.trim().length() > 0) {
g.drawString(currentLine, x, y);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
30872 次 |
| 最近记录: |