該代碼旨在繪製一個矩形,該矩形一次圍繞畫布中心移動一圈。我公司目前擁有的代碼是如何繪製圍繞畫布中心的圓圈移動矩形?
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import javax.swing.Timer;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Q3_Circular extends JComponent {
protected int degree = 0;
protected double xStart;
protected double yStart;
protected Timer timer;
public Q3_Circular() {
timer = new Timer(1000, new TimerCallback()); //creates new times that refreshes every 100 ms, and called the TimerCallback class
timer.start();
}
protected class TimerCallback implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (degree < (2 * Math.PI)){
xStart = getWidth()/2 * Math.cos(degree+1);
yStart = getHeight()/2 * Math.sin(degree+1);
degree+= 1;
repaint();
}
else {
degree += 0;
repaint();
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("AnimatedSquare");
Q3_Circular canvas = new Q3_Circular();
frame.add(canvas);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void paintComponent(Graphics g){
xStart = (double)(getWidth())/2.0 * Math.cos(degree);
yStart = (double)(getHeight())/2.0 * Math.sin(degree);
Graphics2D g2 = (Graphics2D) g;
g2.draw(new Rectangle2D.Double(xStart,yStart, 25,25));
repaint();
}
}
此代碼出現非常迅速地繪製矩形圍繞點(0,0)。我不確定代碼出錯的地方。
您需要知道'Math#cos'和'Math#sin'中的'degree'參數假設爲* Radian *而非Degrees。此外,您應該知道,對於某些輸入,「sin」和「cos」函數的輸出可以是** Negative **。所以你的'xStart'和'yStart'被計算爲負值,然後在你的幀之外繪製。另外,當您在'paintComponent'方法中計算'xStart'和'yStart'時,您將忽略'actionPerformed'方法中的計算。詢問任何問題,如果這些提示沒有幫助。 – STaefi
順便說一句,雖然它沒有回答你的問題,但可能它可以簡化你的代碼。在Graphics2D中,您可以使用仿射變換進行旋轉。他們基本上會讓你擺脫三角函數。請閱讀此處:http://docs.oracle.com/javase/tutorial/2d/advanced/transforming.html –
謝謝,這非常有幫助。我仍然遇到的唯一問題是它圍繞點0,0圍繞點(getWidth()/ 2,getHeight()/ 2)旋轉。 –