哦,男孩,三角是如此的辛苦!我还挺需要一些帮助,这是应该绕屏幕的中心球一个简单的程序...这里是我的代码: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
。 所以我需要建议。我应该改变什么?我的三角学错了吗?等等......
这是一个经典的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
这是错误的。这里没有EDT阻塞问题。对Thread.sleep()的调用位于主线程中,而不是像在链接问题中那样位于EDT中。 – Grodriguez
你说得对。这甚至是最糟糕的。在EDT中不创建帧创建和repaint()调用。并且OP应该只重画'DrawPanel'对象而不是整个框架BTW。无论如何,调用Thread.sleep()的循环根本不是一个好习惯。 OP应该按照建议使用摆动计时器。 @Grodriguez – dic19