java - 如何删除JFrame中绘制的字符串

标签 java string swing jframe

所以基本上我想在 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();
}

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

最佳答案

您需要清除绘制的区域,然后重新绘制字符串。

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

关于java - 如何删除JFrame中绘制的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19553657/

相关文章:

java - 如何在具有多个类的数组中转换对象?

java - 在代码中更新版本存储库中的项目属性

java - 在 Windows 7 上配置 Apache Ant 和 Ivy

java 扫描器忽略 ^ Caret

python - 将两个日期时间连接成字符串日期范围

java - 关闭 JFrame 窗口后启动事件

java - 如果我在 JPopupMenu 外部单击,它不会关闭

java - 打印无法正常工作

在输出中看不到完整的单词

java - Java中如何将10位电话号码解析为整数