iron wud
iron wud

Reputation: 3

Java, Text on Image, update

I want to write some text on a image(BufferedImage), but when the text is updated the new text is written over the old one, e.g. all numbers are written in same place, Can someone help. i'm usins this code:

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

    }



}

Upvotes: 0

Views: 699

Answers (3)

Andrew Thompson
Andrew Thompson

Reputation: 168825

There is no reason to draw the text directly on the image. Simply draw the image to the component Graphics instance then draw the string to the same Graphics.

Upvotes: 1

Aaron Digulla
Aaron Digulla

Reputation: 328594

You must keep an unmodified copy of the original image. Try this pseudocode:

BufferedImage img1 = loadImage();

And in your paint code:

BufferedImage img2 = createEmptyImage( img1 ); // same size, mode and depth
Graphics g = img2.getGraphics();
try {
    g.draw( img1 ); // background
    g.drawString(); // render text on top of it
} finally {
    g.dispose();
}

Upvotes: 1

Attila
Attila

Reputation: 28762

You are drawing the text to the same position, it is bound to overwrite

gi.drawString(r, 20, 20);

You will need to change the vertical coordinate if you want the new text to appear below the old one

Upvotes: 1

Related Questions