【问题标题】:How to delete a drawn string in JFrame如何在 JFrame 中删除绘制的字符串
【发布时间】:2013-10-23 22:41:05
【问题描述】:

所以基本上我想在 JFrame 面板上有一个数字系统。使用此方法将数字显示在框架上。

public static void text(int x, int y, String text)
{
if (instance == null)
  throw new RuntimeException("Must call window method first");
Graphics g = image.getGraphics();
g.setColor(color);
Font font = new Font(null, Font.PLAIN, fontSize);
g.setFont(font);
FontMetrics metrics = g.getFontMetrics();
int actualX = x - metrics.stringWidth(text) / 2;
int actualY = y + metrics.getAscent() / 2;
g.drawString(text, actualX, actualY);

instance.repaint();
}

当数字的值增加时,我希望它用新数字替换上面的数字。我知道必须有办法做到这一点,但有人可以帮我找到它吗?非常感谢。

【问题讨论】:

    标签: java string swing jframe


    【解决方案1】:

    你需要清除绘制的are,然后重新绘制字符串。

    public static void image(int x, int y, int width, int height, String file)
    {
    if (instance == null)
      throw new RuntimeException("Must call window method first");
    Graphics g = image.getGraphics();
    ////
    g.setColor(bgColor);//background color
    g.fillRect(0,0,image.getWidth(),image.getHeigth());//clearing the are by filling a rectangle
    ////
    g.setColor(color);
    Font font = new Font(null, Font.PLAIN, fontSize);
    g.setFont(font);
    FontMetrics metrics = g.getFontMetrics();
    int actualX = x - metrics.stringWidth(text) / 2;
    int actualY = y + metrics.getAscent() / 2;
    g.drawString(text, actualX, actualY);
    
    instance.repaint();
    }
    

    【讨论】:

    • 感谢您的回答,但我把帖子搞砸了。我将第一行放在另一个添加图像的类中。你能帮我处理文字而不是图片吗?
    • 所以这不是一个辛苦的工作,你只需要更改fillRect()的值,我只是给你一个例子,现在如果文本是从x=100开始的,那么只需更改第一个值为 100。您只需要知道每次绘制文本时可能/准确的位置。
    【解决方案2】:

    您不应该使用 getGraphics() 方法进行绘画。为了将来参考,请阅读 Custom Painting 上的 Swing 教程,了解执行此类操作的正确方法。

    但是,您甚至不应该为此要求使用自定义绘画。相反,您应该只使用JLabel。然后,当您想更改字符串时,只需调用标签的setText() 方法即可。

    【讨论】:

      猜你喜欢
      • 2015-07-21
      • 1970-01-01
      • 2014-01-26
      • 1970-01-01
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      • 1970-01-01
      • 2021-04-17
      相关资源
      最近更新 更多