Search code examples
javaimagetimerhide

Java hide images


I'm trying to make a simple program that shows that lets an image bob across the screen. Now iv'e succeded to make an image to go form left to right but now I have like 20 images on the screen.

What I need to get is that when the next image is printed that te previous image is hidden. Also if someone could help me out with printing with a timer it would be great.

Here is my code

package imagemove;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

public class imagemove extends Component {
    private int x;
    private int y;

    BufferedImage img;

    public imagemove() {
       try {
           img = ImageIO.read(new File("F:/JAVA/workspace/Tutorials/src/imagemove/1.jpg"));
       } catch (IOException e) {
       } 

    }


    public void paint(Graphics g) {
        x = 0;
        y = 50;

        for (int number = 1; number <= 15; number++) {
            g.drawImage(img, x, y, this);
            if (x > 1000) {
                x = 0;
            } else {
                x += 100;
            }   

            if(y > 100) {
                y -= 100;
            } else {
                y += 25;
            }
            repaint();
        }
    }


    public static void main(String[] args) { 
        JFrame f = new JFrame("Boot");   
        f.setSize(1000,1000);
        f.add(new imagemove());        
        f.setVisible(true);
    }
}

Solution

  • It works this way; it tested it:

    public class imagemove extends Component {
        private int x;
        private int y;
    
    
        BufferedImage img;
    
        public imagemove() {
           try {
               img = ImageIO.read(new File("F:/JAVA/workspace/Tutorials/src/imagemove/1.jpg"));
           } catch (IOException e) {
           } 
    
           x = 0;
           y = 50;
        }
    
    
        @Override
        public void paint(Graphics g) {
            g.drawImage(img, x, y, this);
            if (x > 1000) {
                x = 0;
            } else {
                x += 100;
            }   
    
        if(y > 100) {
            y -= 100;
        } else {
            y += 25;
        }
    }
    
    
    public static void main(String[] args) { 
        JFrame f = new JFrame("Boot");   
        f.setSize(1000,1000);
        f.add(new imagemove());        
        f.setVisible(true);
    
        for (int number = 1; number <= 15; number++) {
            f.repaint();
    
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {}
        }
    }
    

    }