如何在填充矩形内绘制字符串?

发布于 2024-12-18 07:21:40 字数 34 浏览 2 评论 0原文

我只想在填充黑色的矩形内显示我的字符串。感谢您的帮助!

I just want to display my String inside a rectangle filled with black. Thanks for the help!

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

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

发布评论

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

评论(2

神经大条 2024-12-25 07:21:40

给你:

public class MyPanel extends JPanel{
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawRect(10/*x*/, 10/*y*/, 80/*width*/, 30/*hight*/);
    g.drawString("TextToDraw", 25/*x*/, 25/*y*/);
  }
}

Here you are:

public class MyPanel extends JPanel{
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawRect(10/*x*/, 10/*y*/, 80/*width*/, 30/*hight*/);
    g.drawString("TextToDraw", 25/*x*/, 25/*y*/);
  }
}
七秒鱼° 2024-12-25 07:21:40
public class LabeledRectangle extends Rectangle{

    public LabeledRectangle(int x, int y, int width, int height, String text) {
        super (x, y, width, height);
        this.text = text;

    }

    public void draw(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.draw(new Rectangle2D.Double(x, y, width,height));
        Font font = g2.getFont();
        FontRenderContext context = g2.getFontRenderContext();
        g2.setFont(font);
        int textWidth = (int) font.getStringBounds(text, context).getWidth();
        LineMetrics ln = font.getLineMetrics(text, context);
        int textHeight = (int) (ln.getAscent() + ln.getDescent());
        int x1 = x + (width - textWidth)/2;
        int y1 = (int)(y + (height + textHeight)/2 - ln.getDescent());

        g2.setColor(Color.red);

        g2.drawString(text, (int) x1, (int) y1);
    }
    private String text;
}
public class LabeledRectangle extends Rectangle{

    public LabeledRectangle(int x, int y, int width, int height, String text) {
        super (x, y, width, height);
        this.text = text;

    }

    public void draw(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        g2.draw(new Rectangle2D.Double(x, y, width,height));
        Font font = g2.getFont();
        FontRenderContext context = g2.getFontRenderContext();
        g2.setFont(font);
        int textWidth = (int) font.getStringBounds(text, context).getWidth();
        LineMetrics ln = font.getLineMetrics(text, context);
        int textHeight = (int) (ln.getAscent() + ln.getDescent());
        int x1 = x + (width - textWidth)/2;
        int y1 = (int)(y + (height + textHeight)/2 - ln.getDescent());

        g2.setColor(Color.red);

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