【发布时间】:2013-05-11 09:15:42
【问题描述】:
我正在尝试创建一个程序来运行类似于this video 上的动画,但我无法添加更多方块。我试图将所有方块添加到数组列表中,但我无法弄清楚它的去向。
-
到目前为止,这是我的代码:
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(); } } }
【问题讨论】:
-
1) 对代码块使用一致且符合逻辑的缩进。代码的缩进是为了帮助人们理解程序流程。 2) 你已经描述了一个问题,但到目前为止还没有提出任何问题(更不用说一个具体的、可回答的问题了)。你的问题是什么?
-
谢谢各位。我需要知道如何添加多个正方形