Question

import java.awt.*;
import javax.swing.*;
import java.util.concurrent.TimeUnit;
public class testing extends JPanel{

  //this is the testing game board
 public static void main(String[] args)throws Exception{
  pussy p=new pussy();
  JFrame f=new JFrame("HI");
  f.setSize(500,500);
  f.setVisible(true);
  f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  f.add(p);


 //if hit then repaint
 //testing
  for(int i=0;i<1000;i++){
    TimeUnit.SECONDS.sleep(1);
    p.repaint();}
}





}


  import java.awt.*;
  import javax.swing.*;
  import java.io.*;
  import javax.imageio.*;

  public class pussy extends JPanel{

int x;  //xcoord of pussy
int y;  //ycoord of pussy
int h=500;  // height of the game board 
 int w=500;  // width of the game board
int hp=50;  // height of the pussy
int wp=30;  // width of the pussy
Image image;
pussy(){
try {                           
           image = ImageIO.read(new File("pussy.png"));
      }
       catch (Exception ex) {
           System.out.println("error");
       }         
 }


@Override
   public void paintComponent(Graphics g) {
       nextlevel(h,w); 
       g.drawImage(image,x,y,wp,hp,null);
  }    


   //create a random x,ycoord for the new pussy 
   public void nextlevel(int h, int w){ 
    this.x=(int)(Math.random()*(w-2*wp));
    this.y=(int)(Math.random()*(h-2*hp));


}
 }

My code have 2 class i want my image move but... It Keeps on adding new image on the Frame ,but i always want replace i.e only one image on the screen at a time i use drawoval before it is replacing but this time drawimage is different how can i fix it thank you

Was it helpful?

Solution

  1. Your paintComponent(...) method needs to call the super method, probably as the first method call inside of it's body: super.paintComponent(g)'. This will clear any images drawn previously. This is your main problem.
  2. You shouldn't have sleeps or pauses in your Swing program like you're doing as this will break as soon as you move that code out of main. Instead use a Swing Timer for your animation.

e.g.,

@Override
public void paintComponent(Graphics g) {
  super.paintComponent(g);  // ****** be sure to add this ******
  nextlevel(h,w); 
  g.drawImage(image,x,y,wp,hp,null);
} 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top