Graphics2D.drawString 中的换行符问题

发布于 2024-10-07 01:49:20 字数 219 浏览 6 评论 0 原文

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

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

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\r\n" + newline + "part2", x, y);

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

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

发布评论

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

评论(3

蓝梦月影 2024-10-14 01:49:20

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

它给出以下结果:

在此处输入图像描述

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

which gives the following result:

enter image description here

秋风の叶未落 2024-10-14 01:49:20

我刚刚制作了一种通过给出线宽来自动绘制长文本分割的方法。

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

I just made a method to draw long text spliting automaticaly by giving the line width.

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);
        }
    }
}
套路撩心 2024-10-14 01:49:20

这是我用来在带有选项卡扩展和多行的 JPanel 中绘制文本的片段:

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;

public class Scratch {
    public static void main(String argv[]) {
        JFrame frame = new JFrame("FrameDemo");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel() {
            @Override
            public void paint(Graphics graphics) {
                graphics.drawRect(100, 100, 1, 1);
                String message =
                        "abc\tdef\n" +
                        "abcx\tdef\tghi\n" +
                        "xxxxxxxxdef\n" +
                        "xxxxxxxxxxxxxxxxghi\n";
                int x = 100;
                int y = 100;
                FontMetrics fontMetrics = graphics.getFontMetrics();
                Rectangle2D tabBounds = fontMetrics.getStringBounds(
                        "xxxxxxxx",
                        graphics);
                int tabWidth = (int)tabBounds.getWidth();
                String[] lines = message.split("\n");
                for (String line : lines) {
                    int xColumn = x;
                    String[] columns = line.split("\t");
                    for (String column : columns) {
                        if (xColumn != x) {
                            // Align to tab stop.
                            xColumn += tabWidth - (xColumn-x) % tabWidth;
                        }
                        Rectangle2D columnBounds = fontMetrics.getStringBounds(
                                column,
                                graphics);
                        graphics.drawString(
                                column,
                                xColumn,
                                y + fontMetrics.getAscent());
                        xColumn += columnBounds.getWidth();
                    }
                    y += fontMetrics.getHeight();
                }
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(400, 200);
            }
        };
        frame.getContentPane().add(panel, BorderLayout.CENTER);

        frame.pack();

        frame.setVisible(true);    }
}

它确实看起来像 Utilities.drawTabbedText() 很有前途,但我无法弄清楚它需要什么作为输入。

Here's a snippet I used to draw text in a JPanel with tab expansion and multiple lines:

import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;

public class Scratch {
    public static void main(String argv[]) {
        JFrame frame = new JFrame("FrameDemo");

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel() {
            @Override
            public void paint(Graphics graphics) {
                graphics.drawRect(100, 100, 1, 1);
                String message =
                        "abc\tdef\n" +
                        "abcx\tdef\tghi\n" +
                        "xxxxxxxxdef\n" +
                        "xxxxxxxxxxxxxxxxghi\n";
                int x = 100;
                int y = 100;
                FontMetrics fontMetrics = graphics.getFontMetrics();
                Rectangle2D tabBounds = fontMetrics.getStringBounds(
                        "xxxxxxxx",
                        graphics);
                int tabWidth = (int)tabBounds.getWidth();
                String[] lines = message.split("\n");
                for (String line : lines) {
                    int xColumn = x;
                    String[] columns = line.split("\t");
                    for (String column : columns) {
                        if (xColumn != x) {
                            // Align to tab stop.
                            xColumn += tabWidth - (xColumn-x) % tabWidth;
                        }
                        Rectangle2D columnBounds = fontMetrics.getStringBounds(
                                column,
                                graphics);
                        graphics.drawString(
                                column,
                                xColumn,
                                y + fontMetrics.getAscent());
                        xColumn += columnBounds.getWidth();
                    }
                    y += fontMetrics.getHeight();
                }
            }

            @Override
            public Dimension getPreferredSize() {
                return new Dimension(400, 200);
            }
        };
        frame.getContentPane().add(panel, BorderLayout.CENTER);

        frame.pack();

        frame.setVisible(true);    }
}

It really seemed like Utilities.drawTabbedText() was promising, but I couldn't figure out what it needed as input.

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