2014-01-29 49 views
2
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)); 


} 
} 

我的代碼有2類 我希望我的形象的舉動,但... 它使上框架添加新的圖像,但我總是想更換 即一次只 我之前用它drawoval屏幕上的一個圖像被更換,但這次的drawImage是不同 我該如何解決 謝謝我怎麼能取代舊的圖像使用的drawImage時和重繪

回答

2
  1. paintComponent(...)方法需要調用超級方法,可能作爲它內部的第一個方法調用:super.paintComponent(g)'。這將清除之前繪製的任何圖像。這是你的主要問題。
  2. 你不應該像你在做的那樣在你的Swing程序中休眠或暫停,因爲只要你將代碼移出主體就會中斷。相反,您的動畫使用擺動計時器。

例如,

@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); 
} 
+0

THANKS VY MUCH !!! – user3249877

+0

@ user3249877:非常歡迎! –

相關問題