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 #MATLAB仿真#车辆换道路径规划
    • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
    • ¥15 数据可视化Python
    • ¥15 要给毕业设计添加扫码登录的功能!!有偿
    • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
    • ¥15 微信公众号自制会员卡没有收款渠道啊
    • ¥100 Jenkins自动化部署—悬赏100元
    • ¥15 关于#python#的问题:求帮写python代码
    • ¥20 MATLAB画图图形出现上下震荡的线条
    • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘