2017-04-25 71 views
-1

我是Java新手。我想爲我的項目製作簡單的agario遊戲。但我有一個問題。我想在面板上製作隨機停止圈,但是我的圈子不會停止並更改。我想在面板上製作隨機停止圓圈,但是我的圓圈不停止變化

問題是我想定時器。

class TestPanel extends JPanel implements ActionListener{ 
TestPanel(){ 
    Timer t = new Timer(50,this); 
    t.start(); 
} 

Random rnd = new Random(); 


int r = rnd.nextInt(256); 
int b = rnd.nextInt(256); 
int gr = rnd.nextInt(256); 

Color randomColor = new Color(r,b,gr); 

Ellipse2D.Double ball = new Ellipse2D.Double(0, 0, 40, 40); 
double v = 10; 
public void paintComponent(Graphics g){ 
    super.paintComponent(g); 

    Graphics2D g2 =(Graphics2D)g; 


    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
      RenderingHints.VALUE_ANTIALIAS_ON); 


    g2.setColor(Color.RED); 
    g2.fill(ball);  

    int NumOfCircles = 70; 
    int diameter; 
    int x, y; 


    Graphics2D g3 =(Graphics2D)g; 



    for(int count = 0; count < NumOfCircles; count++){ 
     diameter = rnd.nextInt(10); 
     x = rnd.nextInt(600); 
     y = rnd.nextInt(620); 
     g3.setColor(randomColor); 
     g3.fillOval(x, y, diameter, diameter); 
    } 

    } 


@Override 
public void actionPerformed(ActionEvent arg0) { 
    Point p = getMousePosition(); 
    if(p==null) return; 
    double dx = p.x - ball.x - 20; 
    double dy = p.y - ball.y - 20; 
    if(dx*dx+dy*dy >12){ 
    double a=Math.atan2(dy, dx); 
    ball.x += v * Math.cos(a); 
    ball.y += v * Math.sin(a);} 
    repaint(); 
} 

}

回答

0

的問題是在你的繪圖代碼。您無法控制Swing何時調用繪畫邏輯。所以繪畫代碼應該只繪製基於面板屬性的對象,不應修改屬性。

這意味着:

  1. 不生成隨機值是繪畫方法。

  2. 在你的類的構造函數中,你生成了Circle併爲每個Circle分配了一個默認大小/位置。這些信息然後存儲在一個ArrayList中。然後在paintComponent()方法中,只需遍歷List並繪製每個圓。

  3. TimerActionListener中,您可以遍歷ArrayList並更新每個Circle的位置。然後你在面板上調用repaint(),這樣所有的Circle都會被重新繪製。

例如退房:How to move two circles together in a JFrame from two different classes