Java Swing 尝试用矩形做一个小动画

Java Swing Try to make a little animation with rectangle

我试着做一个迷你游戏,但首先我要学习如何制作动画 :) 这将是一个 2D 游戏。 所以我的问题是,如果我只是尝试绘制一个矩形,当我尝试制作动画时它的工作(我做了很多代码但没有工作:()它不起作用。

有人可以帮助我修复它或添加一些提示我该如何尝试。

public class Window extends JPanel implements ActionListener {

    Timer tm = new Timer(5 , this);

    int x2 = 0 , velX = 2;

    static int x= 500;
    static int y= 500;

    public void paintComponent(Graphics g){

        super.paintComponent(g);

        g.setColor(Color.RED);
        g.fillRect(x2, 30, 30, 30);

        tm.start();

    }

    public Window(){

        JFrame f = new JFrame();
        f.pack();
        f.setTitle("Game");
        f.setSize(x,y);
        f.setVisible(true);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
    }

    /*public void paint(Graphics g){


        Graphics2D g2d = (Graphics2D) g;
        Rectangle rect = new Rectangle(50, 50, 50, 50);


        g2d.translate(25, 25);
        g2d.rotate(Math.toRadians(45));
        g2d.draw(rect);
    }*/

    public static void main(String [] args) throws InterruptedException{
        Game g = new Game();
        g.setName("Test");
        System.out.println(g.getName());
        g.setScore();
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        x2 = x2 + velX;
        repaint();

    }

}

除了您忘记将组件(您将其命名为 Window)添加到容器(在本例中为 JFrame)之外,您的代码工作正常。为此,请在 Window() 构造函数的末尾添加 f.add(this);

查看 swing-components-and-containers 了解更多信息。

另外我建议你看看Double-buffer-in-standard-Java-AWT and Game loops!