gpt4 book ai didi

java - 将方 block 添加到动画中

转载 作者:行者123 更新时间:2023-12-01 14:35:51 26 4
gpt4 key购买 nike

  1. 我正在尝试创建一个程序来运行类似于 this video 上的动画。但我在添加更多方 block 时遇到问题。我尝试将所有方 block 添加到数组列表中,但我无法弄清楚它去了哪里。

  2. 到目前为止,这是我的代码:

    public class Animation extends JFrame{

    CrazySquares square = new CrazySquares();

    Animation(){

    add(new CrazySquares());
    }

    public static void main (String[] args){

    Animation frame = new Animation();
    frame.setTitle("AnimationDemo");
    frame.setLocationRelativeTo(null); // Center the frame
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(250, 250);
    frame.setVisible(true);
    }
    }

    class CrazySquares extends JPanel{


    private final int numberOfRectangles=100;

    Color color=new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256));

    private int x=1;
    private int y=1;
    private Timer timer = new Timer(30, new TimerListener());
    Random random= new Random();
    int randomNumber=1+(random.nextInt(4)-2);

    Random rand= new Random();
    int rando=1+(rand.nextInt(4)-2);


    CrazySquares(){
    timer.start();

    }

    protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    int width=getWidth();
    int height=getHeight();


    g.setColor(color);
    g.fillRect(x+width/2,y+(int)(height*.47), 20, 20);


    }


    class TimerListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e) {

    x += rando;
    y+= randomNumber;
    repaint();

    }


    }

    }

最佳答案

您已经获得了绘制一个矩形的代码,如下:

int width=getWidth();
int height=getHeight();

g.setColor(color);
g.fillRect(x+width/2,y+(int)(height*.47), 20, 20);

现在我建议您将这些值移植到 Square 对象中。或者,更好的是,使用 Rectangle 对象。如果您采用自定义方法:

public class Square
{
public Square(int x, int y, int height, int width)
{
// Store these values in some fields.
}

public void paintComponent(Graphics g)
{
g.fillRect() // Your code for painting out squares.
}
}

然后,您需要做的就是调用某个列表中每个对象的 paintComponent 方法。假设您有一些列表:

List<Square> squares = new ArrayList<Square>();


for(Square sq : squares)
{
sq.paintComponent(g);
}

关于java - 将方 block 添加到动画中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16495582/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com