如何解决这个java.lang.NullPointerException?

时间:2016-12-14 13:32:37

标签: java exception

我想尝试使用JPanel和JFrame在屏幕上放置一个矩形。但我得到java.lang.NullPointerException,我不知道为什么。我的代码:

创建矩形的类:

package com.game.main;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JPanel;

public class Rect extends JPanel {

Graphics a;

public Rect(){      
    a.drawRect(100, 100, 200, 250);
    a.setColor(Color.RED);
    a.fillRect(100, 100, 200, 250);     
    }
}

创建JPanel的类:

package com.game.main;

import javax.swing.JPanel;

public class Inside extends JPanel {

    public Inside(){
        JPanel content = new JPanel();
        Rect rect = new Rect();
        content.add(rect);
    }
}

创建JFrame的类:

package com.game.main;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Window extends Main{

    public static final int Width = 1020, Height = 860;

    public Window(JPanel content){
        JFrame frame = new JFrame("The Game");
        frame.setContentPane(content);
        frame.setSize(Width, Height);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocation(100, 100);
    }

}

把所有东西放在一起的类:

package com.game.main;

public class Main {

    public static void main(String[] args) {
        Inside inside = new Inside();
        Window window = new Window(inside);
    }

}

我对Graphics类也不是很熟悉,所以一点点解释都会很精彩。

谢谢

0 个答案:

没有答案