定时器动画的问题

Problems With Timer Animations

我想做什么: 动画矩形,使它们从屏幕右侧移动到屏幕左侧。下面是绘画代码:

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.Timer;

public class graphics extends JPanel{

    public static Timer a;

    public static int animation = 0;

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.setBackground(new Color(40,40,40));

        g.setColor(new Color(197,255,172));
        g.fillRect(animation, 0, 800, 35);

        g.setColor(new Color(141,229,123));
        g.fillRect(animation, 35, 800, 35);

        g.setColor(new Color(112,183,98));
        g.fillRect(animation, 70, 800, 35);

        g.setColor(new Color(84,137,73));
        g.fillRect(animation, 105, 800, 35);

        g.setColor(new Color(42,68,36));
        g.fillRect(animation, 140, 800, 35);

        g.setFont(new Font("Dekar Light", Font.PLAIN, 30));
        g.setColor(Color.WHITE);
        g.drawString("Graphics Test", 326, 300);

        a = new Timer(1000, new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                repaint();
                int velx = 5;

                animation = animation - velx;
                System.out.println(animation);
            }

        });

        a.start();
    }
}

这是框架:

我的问题:如您所见,矩形移动的距离似乎是上次移动距离的两倍。

我的问题:我做错了什么?我需要知道它是否与我正在使用的计时器或方程式有关。

I need to know if it's something with either the timer

A painting method should only ever do painting!

它不应该启动 Timer。每次绘制组件时,都会启动另一个 Timer,因此最终会生成多个 repaint() 请求。 RepaintManager 然后会将多个请求合并到组件的单个重绘中。

定时器应该在 class 的构造函数中启动,或者您应该创建一个 startAnimation() 方法方法并将其添加到您的面板中。然后可以在框架可见(或根据需要)后调用该方法。

此外,class 名称应始终以大写字符开头。但是,您不应使用 "Graphics",因为已经有一个 Java class 具有该名称。让您的 class 名称更具描述性。