【问题标题】:Is it possible to get the right string size without use paintComponent(Graphics g)?是否可以在不使用paintComponent(Graphics g)的情况下获得正确的字符串大小?
【发布时间】:2018-10-24 09:53:10
【问题描述】:

实际上我有这些方法来获取字符串的宽度/高度大小,两者都需要绘制组件内的命令。但是我想在类构造函数中获取这些值。这可能吗?

public int getStringWidth(Graphics g){
    g2d = (Graphics2D) g;
    metrics = g2d.getFontMetrics(this.font);
    return metrics.stringWidth(this.string);
}

public int getStringHeight(Graphics g){
    g2d = (Graphics2D) g;
    metrics = g2d.getFontMetrics(this.font);
    int height = (int)font.createGlyphVector(metrics.getFontRenderContext(), this.string).getVisualBounds().getHeight();    
    return height;
}

font.createGlyphVector(metrics.getFontRenderContext(), this.string).getVisualBounds().getHeight() 这是我精确计算字符串高度大小的最佳命令,它也需要Graphics g。

【问题讨论】:

  • 我在这段代码中使用 FontMetrics,需要Graphics g 才能工作
  • 我删除了我之前不清楚的评论。见stackoverflow.com/questions/1524855/…
  • 是的,您可以从 Graphics 以外的其他对象获取 FontMetrics 对象:例如 swing 组件。见docs.oracle.com/javase/7/docs/api/java/awt/class-use/…
  • “但是我想在类构造函数中获取这些值。” 为什么?见What is the XY problem?
  • @AndrewThompson,问题是我必须等待 1 次重绘才能获取 Sprites 值,而paintComponent 是在面板上绘制图形而不是初始化图形,我只是想在上面初始化图形类构造函数

标签: java swing


【解决方案1】:

您可以尝试创建一个大小合适的 BufferedImage 并在其上使用 createGraphics() 来获取一个可绘制的实际 Graphics 对象。

BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
Graphics g = img.createGraphics();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 2012-03-17
    • 2012-09-12
    • 2018-03-24
    • 1970-01-01
    相关资源
    最近更新 更多