2016-02-21 36 views
1
package games; 

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*;  

public class viza extends JPanel implements ActionListener {  

/** 
    * 
    */ 
    private static final long serialVersionUID = 1L;  
    int x=0, y=200; 
    Timer tm =new Timer(5,this);  
    public viza(){  
     tm.start();  
    }  
    public void paintComponent(Graphics g){  
     g.setColor(Color.red);  
     g.fillRect(x, y, 20, 20);  
    }  
    public void actionPerformed(ActionEvent e){ 
     x=x+1; 
     y=y+1; 
     if(x>300)  
      x=0;  
     if(x<0) 
      x=0;   
     repaint(); //after x and y are changet then I use repaint(); 
    }  // the frame is created and the new object is added into the frame. 
    public static void main(String[] args){  
     viza a=new viza();  
     JFrame frame = new JFrame();  
     frame.setSize(500,500);   
     frame.add(a);  
     frame.setVisible(true);   
    }  
}[1]  

工作的代碼被用於繪製面板上的填充矩形。但是,當我啓動程序時,對象會移動,但面板不會重新繪製。如果我在程序運行時嘗試調整窗口大小,它會正確加載。只要我停止這樣做,面板或框架(不確定)不再重繪。所以我結束了一條線。重繪()不是在擺動

+0

你覺得x會變成小於0嗎? –

回答

2

在重新繪製矩形的新位置之前,您應清除基礎窗格。

爲了做到這一點,讓super.paintComponent()爲你做的,因爲這將是正確的做法,以風俗畫在任何JComponent

public void paintComponent(Graphics g){  
    super.paintComponent(g); // let it do the default paint 
    g.setColor(Color.red);  
    g.fillRect(x, y, 20, 20);  
} 

你也可能需要一個默認的關閉操作添加到您的框架(在主方法)閉合幀之後退出程序:

frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 

另一個技巧是設置一個更大timeout爲您的定時器,因爲5毫秒發生非常快,而你我們呃可能看不到這個動作。嘗試一些比50100大的東西。

好運。

+0

一如既往,你是對的@AndrewThompson。將編輯答案。 – STaefi

+0

*「將編輯答案。」*很好的編輯。 :) *「一如既往,你是對的..」*哈哈!我希望。如果我是,我會寫下明天的樂透號碼。 ;) –

+0

「如果我是,我會寫下明天的樂透號碼;)」哈哈! :-D – STaefi