简体   繁体   English

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

[英]How to delete a drawn string in JFrame

So basically I want to have a number system on a JFrame panel. 所以基本上我想在JFrame面板上有一个数字系统。 The number is displayed on the frame using this method. 使用此方法将数字显示在框架上。

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

When the value of the number increases I want it to replace the number up there with the new number. 当数字的值增加时,我希望它用新数字替换那里的数字。 I know there has to be a way to do this but could someone help me with finding it? 我知道必须要有一种方法,但是有人可以帮我找到它吗? Thanks so much. 非常感谢。

you need to clear the drawn are, then draw the string again. 您需要清除绘制的区域,然后再次绘制字符串。

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

You should NOT use the getGraphics() method to do painting. 您不应该使用getGraphics()方法进行绘画。 For future reference read the Swing tutorial on Custom Painting for the proper way to do something like this. 为了将来参考,请阅读有关“ 自定义绘画”的Swing教程,以了解执行类似操作的正确方法。

However, you should not even be using custom painting for this requirement. 但是,您甚至不应为此要求使用自定义绘画。 Instead you should just be using a JLabel . 相反,您应该只使用JLabel Then when you want to change the string you just invoke the setText() method of the label. 然后,当您想更改字符串时,只需调用标签的setText()方法即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM