【问题标题】:Move circle in circular path在圆形路径中移动圆圈
【发布时间】:2015-11-16 11:47:05
【问题描述】:

我在 JPanel 中画了一个圆,并使用 Swing Timer 来更新圆的 x,y 坐标。

如何在圆形路径中移动圆。

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setColor(Color.RED);
    Shape planet = new Ellipse2D.Double(x, y, 20, 20);
    g2d.fill(planet);
    g2d.dispose();
}



public void actionPerformed(ActionEvent evt) {
    double R = 200;
    for (double t = 0; t < 2 * Math.PI; t += 0.01) {
        x = R * Math.cos(t) + 0;
        y = R * Math.sin(t) + 0;
        revalidate();
        repaint();
    }
}

【问题讨论】:

  • 使用 Swing 计时器,而不是 for 循环。例如,请查看this link
  • @HovercraftFullOfEels 从外观上看,该函数是绘制圆的,而不是在该帧的轨道中设置位置。
  • @AimanAl-Eryani:代码有更多错误。一方面,它不会编译,因为它使用了一个未声明的变量 g2d,并且因为它使用了一个 for 循环而不关心 Swing 事件线程。根据我的评论,在此代码(或您的解决方案)中,绝对没有在 Swing 事件线程上调用 for 循环的地方,因为由于 Swing 线程规则,这不会导致任何动画。同样,他需要使用 Swing Timer 并告诉我们编译的问题。从表面上看,他曾尝试借用代码,但并不好。他还在处理一个 Graphics obj
  • 一个完整的例子显示在here

标签: java swing java-2d


【解决方案1】:

你真的已经拥有它了。

x = R * Math.cos(t) + 0;
y = R * Math.sin(t) + 0;

那里的 0 代表圆的中心(分别为 x、y)。因此,要在中心 0,0 和半径 R2 的另一个圆轨道的路径中旋转圆。轨道 theta 值 (oTheta) 将每帧增加一次。

double R = 200;
double R2 = 1000;
oTheta += 0.1; // depending on your framerate, the more you add, the faster it will orbit
for (double t = 0; t < 2 * Math.PI; t += 0.01) {
    x = R * Math.cos(t) + 0 + R2 * Math.cos(oTheta);
    y = R * Math.sin(t) + 0 + R2 * Math.sin(oTheta);
    revalidate();
    repaint();
}

【讨论】:

  • 这给了我这个想法。谢谢。
【解决方案2】:

不需要循环。定时器将在指定的时间间隔后调用它并更新 oTheta。

public void actionPerformed(ActionEvent evt) {
    oTheta += 0.01;
    x = radius * Math.cos(oTheta) + centerX;
    y = radius * Math.sin(oTheta) + centerY;
    revalidate();
    repaint();
}

【讨论】:

    猜你喜欢
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 2018-12-15
    相关资源
    最近更新 更多