I'm trying to create a gravity/solar system type simulator in Java, and I'm having trouble painting the circles to the JPanel. Here's my code:

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);
    }
}  

}

Here is the body class:

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;

}

So far it'll only paint the last added object. I want to be able to track and display as many bodies as I can, this seems like the simplest and most CPU efficient solution. Is this the best way to do it? If so, what am I doing wrong?

Thanks in advance!

有帮助吗?

解决方案

  1. Class names start with upper case characters (ie. it should be Body).
  2. Don't use static variables and methods in the class. All your Body objects share the same value as the last Body object created.
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top