以下是一个使用 Java Swing 实现随机移动正方形动画的示例代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class SquareMovingWindow extends JFrame {

    private Timer timer;
    private Random random;
    private int squareX;
    private int squareY;

    public SquareMovingWindow() {
        super('Square Moving Window');
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        setResizable(false);
        getContentPane().setBackground(Color.WHITE);

        random = new Random();

        timer = new Timer(5000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                generateRandomSquare();
            }
        });
        timer.start();
    }

    private void generateRandomSquare() {
        squareX = random.nextInt(getWidth() - 50); // 随机生成正方形的X坐标
        squareY = -50; // 正方形的初始Y坐标设为-50,使其在窗体外面
        repaint();
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);

        g.setColor(Color.RED);
        g.fillRect(squareX, squareY, 50, 50);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SquareMovingWindow().setVisible(true);
            }
        });
    }
}

在这个示例中,我们创建了一个名为 SquareMovingWindow 的类,继承自 JFrame。在构造函数里,我们设置了窗体的一些基本属性,如标题、大小和背景色。我们还初始化了一个 Random 对象,用于生成随机数。

在构造函数中,我们创建了一个 Timer 对象,每隔 5 秒执行一次 ActionListener 中的代码。在 ActionListener 中,我们调用 generateRandomSquare() 方法,生成一个随机的正方形。该方法会生成一个随机的 X 坐标,并将 Y 坐标设为 -50,使其初始位置在窗体外面。

重写 paint() 方法,在其中使用 Graphics 对象绘制正方形。

最后,在 main() 方法中创建了一个 SquareMovingWindow 对象并设置为可见。

Java Swing 实现随机移动正方形动画

原文地址: https://www.cveoy.top/t/topic/uty 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录