我试图用Java创建一个重力/太阳系类型模拟器,而我在将圆圈绘制到JPanel时遇到了麻烦。这是我的代码:
public class GUI {
public static void createAndShowGUI() {
JFrame f = new JFrame("Swing Paint Demo");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new MyPanel());
f.pack();
f.setVisible(true);
}
}
class MyPanel extends JPanel {
ArrayList <body> system = new ArrayList<body>();
public MyPanel() {
add(new body(1000,20,Color.yellow,0,0,100,100));
add(new body(10,5,Color.black,5,0,100,50));
}
public void add(body b){system.add(b);}
public Dimension getPreferredSize() {
return new Dimension(600,600);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (body b: system) {
Ellipse2D object = new Ellipse2D.Double();
object.setFrameFromCenter(
b.getposx() - b.getSize(),
b.getposy() - b.getSize(),
b.getposx(),
b.getposy());
g2.setColor(b.getColor());
g2.fill(object);
}
}
}
这是身体类:
public class body {
public body(){
mass = 100;
size = 1;
velX = 0;
velY = 0;
posX = 0;
posY = 0;
color = Color.white;
}
public body(int mass, int size, Color color, double velX, double velY, double posX, double posY){
body.mass = mass;
body.size = size;
body.color = color;
body.velX = velX;
body.velY = velY;
body.posX = posX;
body.posY = posY;
}
//Getters
public int getMass(){return mass;}
public int getSize(){return size;}
public double getvelx(){return velX;}
public double getvely(){return velY;}
public double getposx(){return posX+velX;}
public double getposy(){return posY+velY;}
public Color getColor(){return color;}
//Setters
public static void setMass(int m){mass = m;}
public static void setSize(int s){size = s;}
public static void setvelx(double v){velX = v;}
public static void setvely(double v){velY = v;}
public static void setposx(double p){posX = p;}
public static void setposy(double p){posY = p;}
public static void setColor(Color c){color = c;}
//Member Variables
private static Color color;
private static int mass;
private static int size;
private static double velX;
private static double velY;
private static double posX;
private static double posY;
}
到目前为止,它只会绘制最后添加的对象。我希望能够跟踪和显示尽可能多的主体,这似乎是最简单,最节省CPU的解决方案。这是最好的方法吗?如果是这样,我做错了什么?
提前致谢!
答案 0 :(得分:2)
Body
)。Body
个对象与创建的最后一个Body
对象共享相同的值。