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();

        }
    }

フレーム内の長方形をアニメーション化しようとしましたが、複数の長方形が繰り返されます。どうしたの?助けて?もう少しクラスがありますが、それらは必要ありません。どうもありがとうございました

4

1 に答える 1

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.
}

スーパー メソッドはコンポーネントの背景を再描画するため、これは重要であり、これは古い四角形を消去するために必要です。

また、このメソッド内にプログラム ロジックがあり、内部から Swing Timer を開始します。これは、決して実行してはならないことです。代わりに、タイマーを開始するための、より制御しやすい場所を見つけてください。

于 2012-07-09T02:13:38.713 に答える