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

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

您需要清除绘制的 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();
}

你不应该使用 getGraphics() 方法来绘画。有关将来的参考,请阅读有关自定义绘画的 Swing 教程,了解执行此类操作的正确方法。

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

最新更新