我从paintcomponent方法中得到了这段代码的空指针异常
public A1Panel() {
final ArrayList<MySnowFlake> myShapes = new ArrayList<MySnowFlake>(); //Stage 1: Replace this line
popup = new JPopupMenu(); //create the popup menu
makePopupMenu();
addMouseListener( new MouseAdapter() {
public void mousePressed(MouseEvent e) {
maybeShowPopup(e);
}
public void mouseReleased(MouseEvent e) {
maybeShowPopup(e);
}
private void maybeShowPopup(MouseEvent e) {
if (e.isPopupTrigger()) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
public void mouseClicked( MouseEvent e ) { //Stage 1: Modify the following statements
myShapes.add(currentIndex, new MySnowFlake(e.getX(), e.getY(), currentLevel, currentLength));
currentIndex += 1;
repaint();
}
});
}
public void paintComponent(Graphics g) {
//g.drawString("" + currentIndex, 50,50);
//Stage 1: Modify the following statements
try{
for (int i = 0; i < currentIndex; i++) {
myShapes.get(i).paint(g);
}
} catch(NullPointerException e){
System.out.println("NullPointerException caught!!");
}
}
我的雪花
public class MySnowFlake {
protected int level; // the recursion level
protected Turtle turtle; // the turtle object
protected double turn = Math.PI/3; // the turning angle
public int length; // the length of the snowflake
public Point p; // the initial position
/** Constructor to create a Snowflake and initialize all values
*/
public MySnowFlake(int x, int y, int level, int length) {
this.level = level;
this.length = length;
p = new Point(x,y);
turtle = new Turtle();
}
public void translate(int dx, int dy){
p.x += dx;
p.y += dy;
}
public void LevelUp(){
level++;
}
public void LevelDown(){
level--;
}
/**
* Recursive draw method
* @param lev - the level of the koch shape
* @param size - the size of the koch shape
*/
public void draw(int lev, double size) {
// 1) define the base case
if(lev < 0){
// 2) define the recursive case
}
/**
* Paint a snowflake
* @param g the graphics control
*/
public void paint(Graphics g) {
double size = length;
// replace this line with recursive calls
g.drawRect(p.x, p.y, level*5, level*5);
// 1) set up the turtle object first
// 2) call the recursive draw method
}
}