问题描述
我正在创建一个简单的太阳系。地球围绕太阳旋转。现在我在试图让月球绕地球旋转时挣扎,同时地球绕太阳旋转。 谢谢您的帮助! 地球代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Earth extends JPanel implements ActionListener{
Timer t=new Timer(100,this);
private int x;
private int y;
private int height;
private int width;
private Color color;
double angle;
public Planetet(int x,int y,int height,int width,Color color) {
this.x=x;
this.y=y;
this.height=height;
this.width=width;
this.color=color;}
public void paint(Graphics g) {
//Extra Code for Screen clearing
g.setColor(getBackground());
boolean rotation=true;
int a,b;
if (rotation) {
int width = getWidth();
int height = getHeight();
a = (int) (Math.cos(angle) * (width / 3) + (width / 2));
b = (int) (Math.sin(angle) * (height / 3) + (height / 2));
} else {
a = getWidth()/2 - gjatsia/2;
b = getHeight()/2 - gjersia/2;
}
g.setColor(ngjyra);
g.filloval(a,b,gjatsia,gjersia);
t.start();
}
public void actionPerformed(ActionEvent e) {
angle+=0.1/2;
if (angle>(2*Math.PI))
angle=0.1;
repaint();}
public static void main (String [] args) {
JFrame MainFrame=new JFrame();
MainFrame.getContentPane().setBackground( Color.black );
MainFrame.setSize(600,600);
Sun sun=new Sun(250,250,50,Color.YELLOW);
Earth earth=new Earth(400,270,20,Color.blue);
Moon moon=new Moon(400,10,Color.GRAY);
MainFrame.add(sun);
MainFrame.setVisible(true);
MainFrame.add(earth);
MainFrame.setVisible(true);
MainFrame.add(moon);
MainFrame.setVisible(true);
}
}
太阳代码:
import javax.swing.*;
import java.awt.*;
public class Sun extends JComponent{
private int x;
private int y;
private int height;
private int width;
private Color color;
double angle;
public Sun(int x,Color color) {
this.x=x;
this.y=y;
this.height=height;
this.width=width;
this.color=color;}
public void paint(Graphics g) {
g.setColor(color);
g.filloval(x,y,height,width);
}}
月球代码(需要更正):
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Moon extends JComponent implements ActionListener{
Timer t=new Timer(100,this);
private int x;
private int y;
private int height;
private int width;
private Color color;
double angle;
public Moon(int x,Color color) {
this.x=x;
this.y=y;
this.height=height;
this.width=width;
this.color=color;}
public void paint(Graphics g) {
int width =getWidth();
int height=getHeight();
int a = (int) (Math.cos(angle) * (width/6) + (width/4));
int b = (int) (Math.sin(angle) * (height/6) + (height/4));
g.setColor(ngjyra);
g.filloval(a,gjersia);
t.start();
}
public void actionPerformed(ActionEvent e) {
angle-=0.5/2;
if (angle>(2*Math.PI))
angle=0.0;
repaint();}}
So this is the output. The earth and the moon both rotate on its own
解决方法
这样想:一切都围绕某物旋转 - A 围绕 B 旋转 - B 围绕 C 旋转 - C 围绕 D 旋转......你如何在代码中表示这种关系?也许通过给每个对象一个它旋转的对象的引用......
此外 - 如果您有多个具有相同或非常相似行为的对象 - 您可以将此行为抽象为父(或抽象)类 - 这样您就无需多次编写相同的代码。
希望能帮助你思考你的代码。