Java 怎么在框中绘制字符串

2019年8月20日22:29:23Java 怎么在框中绘制字符串已关闭评论 300 813字阅读2分42秒

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

 
继续阅读
编程十万个怎么办