import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;

/**
* @Author zyh
* @Date 2020/10/9 18:36
*/
public class SwingUtil {

private static AffineTransform atf = new AffineTransform();

private static FontRenderContext frc = new FontRenderContext(atf, true,
true);

public static int getStringHeight(String str, Font font) {
if (str == null || str.isEmpty() || font == null) {
return 0;
}
return (int) font.getStringBounds(str, frc).getHeight();

}

public static int getStringWidth(String str, Font font) {
if (str == null || str.isEmpty() || font == null) {
return 0;
}
return (int) font.getStringBounds(str, frc).getWidth();
}

/**
* 将形如“#FFFFFF”的颜色转换成Color
*
* @param hex
* @return
*/
public static Color getColorFromHex(String hex) {
if (hex == null || hex.length() != 7) {
try {
throw new Exception("不能转换这种类型的颜色");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
int r = Integer.valueOf(hex.substring(1, 3), 16);
int g = Integer.valueOf(hex.substring(3, 5), 16);
int b = Integer.valueOf(hex.substring(5), 16);
return new Color(r, g, b);
}



}





import lombok.SneakyThrows;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;

/**
* @Author zyh
* @Date 2020/12/3 11:18
*/
public class Window extends JFrame {

private String title="示例窗口";

private String string="纸上得来终觉浅";

private String fontFilePath="D:\\company\\font\\hanyizhengyuanzitidabao_downcc.com\\HYZhengYuan-35W.ttf";

public Window(){

}

public void init() throws IOException, FontFormatException {
this.setTitle(title);
this.setSize(800,400);
this.setLocation(800,200);
this.setVisible(true);
//this.setVisible(false);

Font font = Font.createFont(Font.TRUETYPE_FONT, new File(fontFilePath));
Font font1 = font.deriveFont(Font.BOLD, 16);
this.setFont(font1);
}

@SneakyThrows
public void paint(Graphics graphics){
super.paint(graphics);
graphics.drawString(string,100,100);
//graphics.drawString(string,100,100);

//加载本地字体文件
Font font = Font.createFont(Font.TRUETYPE_FONT, new File(fontFilePath));
//为自定义字体设置字号
Font font1 = font.deriveFont(Font.BOLD, 16);
//计算 宽高
int stringWidth = SwingUtil.getStringWidth(string, font1);
int stringHeight = SwingUtil.getStringHeight(string, font1);

System.out.println("w:"+stringWidth+",h:"+stringHeight);

/*int stringWidth = graphics.getFontMetrics().stringWidth(string);
System.out.println("name:"+name+",w:"+stringWidth);*/
}

public void destroy(){

this.dispose();//关闭窗口

}

public static void main(String[] args) throws IOException, FontFormatException, InterruptedException {

Window window=new Window();
window.init();

Thread.sleep(1000*60);

window.destroy();

}

}