2013-06-03 80 views
1

你好我对Java相当陌生,我一直在学习图形我做了一个代码,显示一个球移动,这个我明白如何使容易。但是当我尝试制作多个球时,它会变得复杂,我应该如何去做,任何人都可以解释一下吗? 基本上我想使用此代码来制作多个球,但我不明白如何。 这是我迄今所取得的代码:如何将多个移动对象绘制到屏幕上

public class Main { 

    public static void main(String args[]) { 
     Ball b = new Ball(); 


     JFrame f = new JFrame(); 
     f.setSize(1000, 1000); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.setVisible(true); 
     f.add(b); 



    } 

} 

    public class Ball extends JPanel implements ActionListener{ 

    Timer t = new Timer(5 , this); 

    int x = 0, y = 0,speedx = 2, speedy = 2; 



    public void paintComponent(Graphics g){ 
     super.paintComponent(g); 
     g.setColor(Color.CYAN); 
     g.fillOval(x, y, 20, 20); 
     t.start(); 
    } 

    public void actionPerformed(ActionEvent e) { 
     x += speedx; 
      y += speedy; 
      if(0 > x || x > 950){ 
       speedx = -speedx; 
      } 
      if(0 > y || y > 950){ 
       speedy = -speedy; 
      } 
      repaint(); 
    } 

} 
+1

要小心名为'x'&'y'的变量,它们可能会导致系统的其他部分出现问题,因为'JPanel'实际上有它自己的(私有)变量 - 命名相同 - 问题出现在人们重写' getX/Y'方法,但你应该小心;) – MadProgrammer

+0

[示例](http://stackoverflow.com/questions/13022754/java-bouncing-ball/13022788#13022788),[示例](http:// stackoverflow.com/questions/14593678/multiple-bouncing-balls-thread-issue/14593761#14593761),[示例](http://stackoverflow.com/questions/14886232/swing-animation-running-extremely-slow/14902184 #14902184),[示例](http://stackoverflow.com/questions/12642852/the-images-are-not-loading/12648265#12648265);) – MadProgrammer

+0

@MadProgrammer好的建议,从来没有想到的! – Mordechai

回答

2

不要在你的paintComponent(...)方法以往任何程序逻辑语句。从该方法中摆脱计时器的启动方法。您无法完全控制何时甚至是否调用该方法。

如果你想显示多个球,那么给你的GUI一个球的ArrayList,然后遍历它们,在paintComponent中绘制它们。将它们移动到定时器中。

+0

@joleMola你可能还想看看[Initial Threads](http://docs.oracle.com/javase/)教程/ uiswing /并发/ initial.html) – MadProgrammer

相关问题