Java 怎么在框中绘制字符串

2019年8月20日22:29:23 评论 23

1.简介

Java 怎么在框中绘制字符串?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;

public class Main {
    
    static void drawCenteredString(Graphics g, Rectangle rect, String str) {
        Graphics2D g2d = (Graphics2D) g;
        FontMetrics fm = g2d.getFontMetrics();
        Rectangle2D r = fm.getStringBounds(str, g2d);
        int dx = (int) ((rect.getWidth() - (int) r.getWidth()) / 2);
        int dy = (int) ((rect.getHeight() - (int) r.getHeight()) / 2 + fm
                .getAscent());
        g.drawString(str, rect.x + dx, rect.y + dy);
    }

    static void drawCenteredString(Graphics g, int x, int y, String str) {
        Graphics2D g2d = (Graphics2D) g;
        FontMetrics fm = g2d.getFontMetrics();
        Rectangle2D r = fm.getStringBounds(str, g2d);
        int nx = (int) (x - (r.getWidth() / 2));
        int ny = (int) (y - (r.getHeight() / 2) + fm.getAscent());
        g.drawString(str, nx, ny);
    }
}

 

3.总结

示例代码演示了 Java 怎么在框中绘制字符串,具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: