Java 机器人出现 NullPointerException 错误

Java NullPointerException error with robot

我正在为学校制作 Space Invaders 的仿制品,我正在尝试创建会随着时间推移而磨损的防护罩。我试图通过放置与背景颜色相同的图像来做到这一点,然后镜头将忽略橙色并击中绿色,继续使用上面的图像。我在处理此部分时不断收到此错误:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at GamePanel.badShotMove(SpaceInvaders.java:173)
at SpaceInvaders.actionPerformed(SpaceInvaders.java:55)
at javax.swing.Timer.fireActionPerformed(Timer.java:313)
at javax.swing.Timer$DoPostEvent.run(Timer.java:245)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:744)
at java.awt.EventQueue.access0(EventQueue.java:97)
at java.awt.EventQueue.run(EventQueue.java:697)
at java.awt.EventQueue.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:714)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

this指向的区域是我程序的最后一个括号,也是我调用方法的一行。

public void badShotMove(){

    for(int i=0;i<badShotList.size();i++){
        badShotList.get(i)[y]+=5;

        //delete shot when out of screen
        if(badShotList.get(i)[y]>=getHeight()){
            badShotDelete(i);
        }
    }
    try {
        Robot robot = new Robot();
    } catch (AWTException e) {
        throw new RuntimeException(e);
    }
    //delete shot when hitting bunker
    for(int i=0;i<badShotList.size();i++){
        Color pixelColor = robot.getPixelColor(badShotList.get(i)[x],badShotList.get(i)[y]);
        if(pixelColor.getRed()==0&&pixelColor.getGreen()>=250&&pixelColor.getBlue()==0){
            boomList.add(badShotList.get(i));
            badShotDelete(i);
        }
    }
}

请帮忙 谢谢

替换这段代码

try {
    Robot robot = new Robot();
} catch (AWTException e) {
    throw new RuntimeException(e);
}

Robot robot;
try {
    robot = new Robot();
} catch (AWTException e) {
    throw new RuntimeException(e);
}

基本上,您的问题是 Robot 是在您的 try{} 中定义的,但变量在它之外没有任何意义。因此,你得到一个 NullPointerException.