繁体   English   中英

线程“main”中的异常java.lang.NullPointerException对于初学者[重复]

[英]Exception in thread "main" java.lang.NullPointerException For Beginner [duplicate]

我知道这已经被告知很多次了,但我已经用 Java 编程了大约 3 周,而且我只是在制作一些东西时玩得很开心。 人们所做的大多数其他报告都没有解决我的问题。 屏幕显示但不是矩形。 这是我的代码:

import java.awt.Rectangle;
import javax.swing.JFrame;
import java.awt.Color;

public class something {
    public static int SCREEN_WIDTH = 500;
    public static int SCREEN_HEIGHT = 500;
    public static int Y = 10;
    public static int X = 10;
    public static int Width = 50;
    public static int Height = 50;
    public static Color player_color = Color.black;
    public static Graphics g;

    public static void screen() {
        JFrame screen = new JFrame();
        screen.setVisible(true);
        screen.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
        screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        screen.setTitle("test");
        screen.setResizable(false);
    }

    public static void player() {
        Rectangle r = new Rectangle(Y, X, Width, Height);
        g.fillRect((int)r.getX(), (int)r.getY(), (int)r.getWidth(), (int)r.getHeight());
        g.setColor(player_color);
    }

    public static void main(String[] args) {
        screen();
        player();
    }
}

顺便说一下,我正在使用 Eclipse,我认为问题意味着我使用的是一个具有空值的值? 如果我错了纠正我。

您的 g 为空且未初始化为任何内容,因此您在访问 fillRect() 方法时获得了空指针。

您可以在类级别使用扩展小程序并覆盖绘制方法()。

public class something extends Applet {
    public static int SCREEN_WIDTH = 500;
    public static int SCREEN_HEIGHT = 500;
    public static int Y = 10;
    public static int X = 10;
    public static int Width = 50;
    public static int Height = 50;
    public static Color player_color = Color.black;

    @Override
    public void paint(Graphics g) {
        JFrame screen = new JFrame();
        screen.setVisible(true);
        screen.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
        screen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        screen.setTitle("test");
        screen.setResizable(false);
        Rectangle r = new Rectangle(Y, X, Width, Height);
        g.fillRect((int) r.getX(), (int) r.getY(), (int) r.getWidth(), (int) r.getHeight());
        g.setColor(player_color);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM