public
anonymous / SimulationComponent
Created

  • Download Gist
SimulationComponent
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
public class SimulationComponent extends JComponent
implements ActionListener{
JButton moveButton;
EcoSystem eSystem;
ArrayList<Animal> animals = new ArrayList<Animal>();
public SimulationComponent() {
moveButton = new JButton("Move things!");
setLayout(new FlowLayout());
add(moveButton);
moveButton.addActionListener(this);
}
public void addElement(Animal animal){
animals.add(animal);
}
public void addSimulation(EcoSystem eSystem){
this.eSystem = eSystem;
}
 
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
Shape shapes[] = new Shape[animals.size()];
for(int i = 0; i < animals.size(); i++){
//NullPointerException on the next line.
shapes[i] = new Ellipse2D.Float(animals.get(i).getLocationX(),
animals.get(i).getLocationY(), 20, 20);
if(animals.get(i) instanceof Fox)
{
g2.setPaint(Color.orange);
}
else
if(animals.get(i) instanceof Rabbit){
if (animals.get(i).getColor() == AnimalColor.BLACK){
g2.setPaint(Color.black);
}
else{
g2.setPaint(Color.white);
}
}
g2.fill(shapes[i]);
}
}
 
public void actionPerformed(ActionEvent e){
if(e.getSource() == moveButton){
eSystem.moveAnimals();
repaint();
}
}
}
modified ecosystem
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
public class EcoSystem {
private EcoFrame eFrame;
/*private Rabbit peter = new Rabbit();
private Rabbit benjamin = new Rabbit();
private Fox todd = new Fox();
*/
public Animal anim[] = new Animal[10];
public Rabbit r1, r2, r3, r4, r5, r6, r7, r8= new Rabbit();
public Fox f1, f2 = new Fox();
EcoSystem() {
anim[0] = r1;
anim[1] = r2;
anim[2] = r3;
anim[3] = r4;
anim[4] = r5;
anim[5] = r6;
anim[6] = r7;
anim[7] = r8;
anim[8] = f1;
anim[9] = f2;
}
 
public void setUp(){
for (int i=0; i<10; i++) {
eFrame.addElementToSimulation(anim[i]);
}
}
public void addDisplay(EcoFrame eFrame){
this.eFrame = eFrame;
}
public void moveAnimals(){
for (int i=0; i<10; i++) {
anim[i].move();
}
}
}
original ecosystem
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
public class EcoSystem{
private EcoFrame eFrame;
private Rabbit peter = new Rabbit();
private Rabbit benjamin = new Rabbit();
private Fox todd = new Fox();
public void setUp(){
eFrame.addElementToSimulation(peter);
eFrame.addElementToSimulation(benjamin);
eFrame.addElementToSimulation(todd);
}
public void addDisplay(EcoFrame eFrame){
this.eFrame = eFrame;
}
public void moveAnimals(){
peter.move();
benjamin.move();
todd.move();
peter.eat();
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.