for(creature a : horde.creatures){
总是抛出一个nullpointer,即使我之前定义过它:
private swarm horde;
这是群类:
public class swarm {
public creature creatures[] = new creature[100];
}
这只是一系列生物:
public class creature {
Random r = new Random();
public boolean hostile = r.nextBoolean();
public double[] velocity = new double[2];
public double[] position = new double[2];
整个窗口类:
package de.towdo.intellia;
import java.awt.*;
import javax.swing.*;
final public class window {
JFrame frame;
DrawPanel drawPanel;
private swarm horde;
public static void main(String[] args){
new window().go();
}
private void go(){
frame = new JFrame("Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawPanel = new DrawPanel();
frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
frame.setVisible(true);
frame.setResizable(false);
frame.setSize(500, 500);
frame.setLocation(340, 55);
moveIt();
}
class DrawPanel extends JPanel{
public void paintComponent(Graphics g){
for(creature a : horde.creatures){
if(a.hostile){
g.setColor(Color.RED);
}
else{
g.setColor(Color.GREEN);
}
g.fillRect((int)a.position[0], (int)a.position[1], 1, 1);
}
}
}
private void moveIt(){
while(true){
try {
Thread.sleep(10);
}
catch(Exception exc){
exc.printStackTrace();
}
frame.repaint();
}
}
}