2013-11-28 63 views
1

哦,男孩,三角是如此的辛苦!我还挺需要一些帮助,这是应该绕屏幕的中心球一个简单的程序...这里是我的代码:Java AWT旋转球

import java.awt.*; 

import javax.swing.*; 


public class Window { 
private int x; 
private int y; 
private int R = 30; 
private double alpha = 0; 

private final int SPEED = 1; 
private final Color COLOR = Color.red; 

public static void main(String[] args) {  
    new Window().buildWindow(); 
} 

public void buildWindow() { 
    JFrame frame = new JFrame("Rotation"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setSize(800,600); 
    frame.setVisible(true); 
    frame.add(new DrawPanel()); 
    while(true) { 
     try { 
      Thread.sleep(60); 
      alpha += SPEED; 
      frame.repaint(); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 

} 

@SuppressWarnings("serial") 
class DrawPanel extends JPanel { 


    @Override 
    public void paintComponent(Graphics g) { 
     g.setColor(Color.blue); 
     Font font = new Font("Arial",Font.PLAIN,12); 
     g.setFont(font); 
     g.drawString(String.format("Angle: %.2f ", alpha), 0, 12); 

     g.setColor(Color.black); 
     g.drawLine(this.getWidth()/2,0, this.getWidth()/2, this.getHeight()); 
     g.drawLine(0, this.getHeight()/2, this.getWidth(), this.getHeight()/2); 

     x = (int) ((this.getWidth()/2 - R/2) + Math.round((R + 20) * Math.sin(alpha))); 
     y = (int) ((this.getHeight()/2 - R/2) + Math.round((R + 20) * Math.cos(alpha))); 

     g.setColor(COLOR); 
     g.fillOval(x, y, R, R); 
    } 
} 
} 

这段代码看起来像它的工作,但我已经将角度α信息打印到屏幕上。当我注释掉alpha+=SPEED并手动输入角度时,它看起来不像是在工作。屏幕上的角度与该角度不对应alpha。 所以我需要建议。我应该改变什么?我的三角学错了吗?等等......

+1

这是一个经典的EDT(Event Dispatching Thread)阻塞问题,由Thread.sleep()调用引起。看看** [这个问题](http://stackoverflow.com/questions/20219885/forcing-a-gui-update-inside-of-a-thread-jslider-updates/20220319#20220319)** for有关避免在EDT中使用'Thread.sleep()'的更多信息。如上所示,使用** [Swing Timer](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html)**执行定期更新。 – dic19

+0

这是错误的。这里没有EDT阻塞问题。对Thread.sleep()的调用位于主线程中,而不是像在链接问题中那样位于EDT中。 – Grodriguez

+0

你说得对。这甚至是最糟糕的。在EDT中不创建帧创建和repaint()调用。并且OP应该只重画'DrawPanel'对象而不是整个框架BTW。无论如何,调用Thread.sleep()的循环根本不是一个好习惯。 OP应该按照建议使用摆动计时器。 @Grodriguez – dic19

回答

2

三样东西这里要注意:

  1. 我假设你alpha变量是度,因为你是在每一步加20。然而,Math.sin()Math.cos()方法期望以弧度表示角度。
  2. 通常0度(或0拉德)表示在“3点钟”的位置。为此,您需要切换sincos调用。
  3. 反向的y方程式符号占的事实,y坐标在屏幕的顶部开始向下增加

有了这些修改,你的代码将作为你希望:

double rads = (alpha * Math.PI)/180F; 
x = (int) ((this.getWidth()/2 - R/2) + Math.round((R + 20) * Math.cos(rads))); 
y = (int) ((this.getHeight()/2 - R/2) - Math.round((R + 20) * Math.sin(rads))); 
+0

你是对的。我测试过它,它的工作原理:) – kai

+0

这是从笛卡尔转换为极坐标的标准方式,零度角表示在“3点钟”位置(http://en.wikipedia.org/wiki/ Polar_coordinate_system) – Grodriguez

+0

还有一件事,当360达到360度时需要将角度重置为0(因为整圆是360度)? –