gpt4 book ai didi

java - 如何计算以像素为单位的字符串宽度?

转载 作者:行者123 更新时间:2023-11-29 08:14:18 25 4
gpt4 key购买 nike

如何计算以 px 为单位的字符串宽度?我有面板,我尝试像(JPanel 上的这个引用)

FontMetrics gp = this.getGraphics().getFontMetrics();
int x=gp.stringWidth("test");

但是 getGraphics 总是返回 null,因为面板还不可见。如何解决这个问题?

最佳答案

您应该在 Graphics 实例存在的 paint()paintComponent() 方法之一中执行此操作。

或者您可以创建一个 BufferedImage 并调用 getGraphics()

关于java - 如何计算以像素为单位的字符串宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5729890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com