qq_42417143 2019-03-02 15:35 采纳率: 66.7%
浏览 279

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;
    }
}

图片说明

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 ubuntu虚拟机打包apk错误
    • ¥199 rust编程架构设计的方案 有偿
    • ¥15 回答4f系统的像差计算
    • ¥15 java如何提取出pdf里的文字?
    • ¥100 求三轴之间相互配合画圆以及直线的算法
    • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
    • ¥15 名为“Product”的列已属于此 DataTable
    • ¥15 安卓adb backup备份应用数据失败
    • ¥15 eclipse运行项目时遇到的问题
    • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发