Java SE 中 g.drawString 中的换行和制表符间距

发布于 2024-12-23 10:31:45 字数 693 浏览 2 评论 0原文

我分别获得了这些换行符和换行符的编码。制表符间距。

行间距:

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());
    }
} 

制表符间距:

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

如何组合这些代码?

我想要输出 g.drawString("Line 1\t:Words\t\nLine 2\t:\tWords", x, y); : 喜欢;

Line 1 [tab space]: [tabspace] Words
Line 2 [tab space]: [tabspace] Words

I got the coding separately for these Line breaking & Tab Spacing.

Line Spacing:

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());
    }
} 

Tab Spacing:

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

How can I combine this codes?

Where I want the out put of g.drawString("Line 1\t:Words\t\nLine 2\t:\tWords", x, y); :
Like;

Line 1 [tab space]: [tabspace] Words
Line 2 [tab space]: [tabspace] Words

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无力看清 2024-12-30 10:31:45
private void drawString(Graphics g, String text, int x, int y) {
    for (String line : text.split("\n")) {
        drawtabString(g, line, x, y += g.getFontMetrics().getHeight());
    }
} 

注意:在方法调用中嵌入对 y 变量的修改会让人感到困惑。我会将其分成 2 条指令,以使代码更加明显:

drawtabString(g, line, x, y);
y += g.getFontMetrics().getHeight();

PS:您确定不想简单地使用 JTextArea 吗?

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

Note: embedding the modification of the y variable inside the method call makes it confusing. I would separate it into 2 instructions to make the code more obvious:

drawtabString(g, line, x, y);
y += g.getFontMetrics().getHeight();

PS: are you sure you don't want to simply use a JTextArea?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文