SwingUtilities.invokeLater的lambda表达式,空指针问题?

class MovingShape11 extends Thread {
private int x,y,dx,dy,w,h;
private int type;
private int speed = 10;
Color color;
JFrame app;

public MovingShape11(JFrame app) {
    this.app = app;
    this.x = (int) (Math.random() * app.getSize().width);
    this.y = (int) (Math.random() * app.getSize().height);
    this.dx = (int) (Math.random() * speed);
    this.dy = (int) (Math.random() * speed);
    this.w = (int) (Math.random() * 40);
    this.h = (int) (Math.random() * 40);
    this.type = (int) (Math.random() * 3);
    // this.color=new
    // Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255));
}

public void run() {
    while (true) {
        SwingUtilities.invokeLater(() -> {
            this.drawShape();
        });
        try {
            Thread.sleep(130);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}

void drawShape() {
    x += dx;
    y += dy;
    Graphics g = app.getGraphics();
    if (x < 0 || x > app.getSize().width)
        dx = -dx;
    if (y < 0 || y > app.getSize().height)
        dy = -dy;
    switch (type) {
    case 0:
        g.drawOval(x, y, w, h);
        color = Color.blue;
        g.setColor(color);
        g.fillOval(x, y, w, h);
        break;
    case 1:
        g.drawRect(x, y, w, h);
        color = Color.green;
        g.setColor(color);
        g.fillRect(x, y, w, h);
        break;
    case 2:
        g.drawOval(x, y, w, h);
        color = Color.orange;
        g.setColor(color);
        g.fillOval(x, y, w, h);
        break;
    case 3:
        g.drawRect(x, y, w, h);
        color = Color.gray;
        g.setColor(color);
        g.fillRect(x, y, w, h);
        break;
    default:
        break;
    }
}

图片说明

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问