JAVA使用awt画点报空指针错误
用java的awt写了个画点的小程序,点一下鼠标画一个,不保存已经画过的点import java.awt.*;
import java.awt.event.*;
class Modela extends Frame{
Point pp;
public void launch(){
this.setLayout(null);
this.setBounds(100, 100, 500, 500);
this.setBackground(Color.BLACK);
MMo mm = new MMo();
this.addMouseListener(mm);
this.setVisible(true);
}
public void setPoint(Point p){
this.pp=p;
}
public void paint(Graphics c){
c.setColor(Color.ORANGE);
c.fillOval(pp.x,pp.y,15,15);
}
}
class MMo extends MouseAdapter{
public void mousePressed(MouseEvent e){
Modela mol = (Modela)e.getSource();
mol.setPoint(new Point(e.getX(),e.getY()));
mol.repaint();
}
}
public class MouseAgain {
public static void main(String[] args) {
new Modela().launch();
}
}
程序可以执行,但是会报错Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException。
我不知道是哪里引起了空指针的问题,求指导! --------------------编程问答-------------------- new Modela()
没有设置Point
调用下这个
public void setPoint(Point p){
this.pp=p;
} --------------------编程问答-------------------- 楼主将第四行代码
Point pp ;
改为
Point pp = new Point();
就不会报空指针了 --------------------编程问答--------------------
但如果将代码改为
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Model extends Frame{
ArrayList<Point> points=null;
public void launch(){
this.setBounds(300,300,800,800);
points = new ArrayList<Point>();
this.setLayout(null);
this.setBackground(Color.BLACK);
Moi mo = new Moi();
this.addMouseListener(mo);
this.setVisible(true);
}
public void addpoint(Point t){
points.add(t);
}
public void paint(Graphics c){
Iterator i = points.iterator();
while(i.hasNext()){
Point p = (Point)i.next();
Color col= c.getColor();
c.setColor(Color.GREEN);
c.fillOval(p.x,p.y, 10, 10);
}
}
}
class Moi extends MouseAdapter{
public void mousePressed(MouseEvent e){
Model d = (Model)e.getSource();
d.addpoint(new Point(e.getX(),e.getY()));
d.repaint();
}
}
public class Mouse {
public static void main(String[] args) {
new Model().launch();
}
}
用一个ArrayList保存了Point,为什么在初始调用时就不会报空指针错误? --------------------编程问答-------------------- 哥们,frame的刷新会调用 public void paint(Graphics c){
c.setColor(Color.ORANGE);
c.fillOval(pp.x,pp.y,15,15);
},所以,你在创建frame后,如果没有点击鼠标你的pp是空的,自然会空指针,至于你后面用一个ArrayList保存了Point,为什么在初始调用时就不会报空指针错误?是应为你初始化了points = new ArrayList<Point>();当调用到paint的时候发现points 的长度是0,这时候不会调用 c.fillOval(pp.x,pp.y,15,15);当然不空指针了
补充:Java , Java SE