2015-11-07 112 views
0

我正在試圖在畫布中的一個圓圈內移動一個正方形。我已經得到了一個方框在框架內來回移動,但我在佈置圓周運動時遇到了一些困難。我創建了一個變量theta,其中擺動計時器發生變化,因此改變了形狀的整體位置。但是,當我運行它時,沒有任何反應我也不確定是否應該使用雙精度或整數,因爲drawRectangle命令只接受整數,但數學足夠複雜,需要雙精度值。這是我到目前爲止有:如何在一個圓圈中製作java形狀動畫?

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

public class Circle extends JPanel implements ActionListener{ 

Timer timer = new Timer(5, this); 
Double theta= new Double(0); 
Double x = new Double(200+(50*(Math.cos(theta)))); 
Double y = new Double(200+(50*(Math.sin(theta)))); 
Double change = new Double(0.1); 
int xp = x.intValue(); 
int yp = y.intValue(); 

public void paintComponent(Graphics g){ 
    super.paintComponent(g); 
    g.setColor(Color.BLUE); 
    g.fillRect(xp, yp, 50, 50); 
    timer.start(); 
} 

public void actionPerformed(ActionEvent e) { 

    theta=theta+change; 
    repaint(); 
} 

public static void main(String[] args){ 
    Circle a = new Circle(); 
    JFrame frame = new JFrame("Circleg"); 
    frame.setSize(600, 600); 
    frame.setVisible(true); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.add(a); 

} 

}

回答

1
theta=theta+change; 
repaint(); 

你不改變XP,YP值。他們不會因爲theta值的變化而自我更新自己。

將計算x/y位置的代碼移動到paintComponent()方法中。

Double x = new Double(200+(50*(Math.cos(theta)))); 
Double y = new Double(200+(50*(Math.sin(theta)))); 
int xp = x.intValue(); 
int yp = y.intValue(); 
g.fillRect(xp, yp, 50, 50); 

此外,

timer.start(); 

在畫法不啓動定時器。繪畫方法僅適用於繪畫。

定時器應該在你的類的構造函數中啓動。