2012-07-09 30 views
2

這是我的代碼!重複矩形而不是移動動畫

package softwarea1; 
import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.Timer; 

/* 
* To change this template, choose Tools | Templates 
* and open the template in the editor. 
*/ 

/** 
* 
* @author Leo 
*/ 
//534 
public class Simulation extends JPanel implements ActionListener 
{ 
    DataModels dm; 
    Timer tm = new Timer(20, this); 
    private int velX = 2; 
    private int a = 0; 

    public void create() 
    { 

     Simulation sm = new Simulation(dm); 
     JFrame simulation = new JFrame(); 
     simulation.setTitle("Traffic light and Car park Siumulation"); 
     simulation.setSize(600,600); 
     simulation.setResizable(false); 
     simulation.setVisible(true); 
     simulation.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     simulation.add(sm); 
    } 
    public void paintComponent(Graphics g) 
    { 



     // Moving Rectangle 
     g.setColor(Color.RED); 
     g.fillRect(a ,300, 1 ,30); 
     tm.start(); 
    } 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     a += velX; 
     repaint(); 
    } 


} 

主類的位置:

public class StartProj { 
     public static void main(String[] args) { 
      DataModels dm = new DataModels(); 
      Simulation sm = new Simulation(dm); 
      sm.create(); 

     } 
    } 

我嘗試在幀動畫的矩形但是它重複多次的矩形。 什麼問題?幫我? 我有更多的課程,但他們沒有必要。非常感謝您

回答

6

paintComponent(...)方法需要調用父類的第一線法:

public void paintComponent(Graphics g) 
{ 
    super.paintComponent(g); // **** add this 
    // Moving Rectangle 
    g.setColor(Color.RED); 
    g.fillRect(a ,300, 1 ,30); 
    // tm.start(); // **** get rid of this. 
} 

這是重要的,因爲超級方法重繪組件的背景,而這是需要擦除舊的矩形。

此外,你有這個方法裏面的程序邏輯,你從裏面開始一個擺動計時器,應該做的從來沒有被完成。相反,找到一個更好的可控地點來啓動你的計時器。

+2

肯定要兌現[不透明度](http://java.sun.com/products/jfc/tsc/articles/painting/index.html#props)屬性。 – trashgod 2012-07-09 02:16:41

+1

@CaoLinhTruong:如果重寫[getPreferredSize()](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#getPreferredSize()),將會更明智(')/ setVisible(...)'調用之前,在'JFrame'上設置大小,並使其成爲習慣,在JFrame上添加組件。在重寫'paintComponent(...)'時,要尊重ENCAPSULATION的原則,它是'protected void'而不是'public void'這些都是很好的編程實踐:-) – 2012-07-09 04:17:11