我想在图像(BufferedImage)上写一些文本,但是当文本更新时,新文本会覆盖旧文本,例如所有数字都写在同一个地方,有人可以帮忙。我正在使用这段代码:
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class Prove extends JPanel {
int size = 800;
private BufferedImage sc ;
JLabel label ;
private int counter =0 ;
public Prove()
{
JFrame frame = new JFrame();
frame.getContentPane().add(this);
frame.setSize(2*size, size);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
try{ sc = ImageIO.read(new File("Images/ser.jpg"));
label =new JLabel(new ImageIcon(sc));
this.add(label);
}catch(IOException e){}
}
public void paintComponent(Graphics g)
{
g.setColor(Color.GRAY);
g.fillRect(0,0, getWidth(),getHeight()); //prapavijen
Graphics2D g2 = (Graphics2D)g;
paintScore(g2);
}
public void paintScore(Graphics g2)
{
if(sc != null)
{
Graphics gi = sc.createGraphics();
gi.setFont(new Font("Times New Roman", Font.BOLD, 20));
String r = counter+"";
gi.drawString(r, 20, 20);
counter ++;
this.repaint();
try{Thread.sleep(500);}
catch(InterruptedException e){}
System.out.println(counter);
}
}
public static void main(String[] args)
{
new Prove();
}
}