使用paintComponent(Graphics g)绘制组件,其中g是局部变量

时间:2014-12-10 16:04:25

标签: java nullpointerexception paintcomponent

使用paintComponent(Graphics g)绘制组件,其中g是局部变量。我的问题是每当我这样做它给我一个nullPointerException!我希望以后能够用另一种方法输出新数据,所以我需要将它存储为可以在以后更改的工具。

Map() {
    setPreferredSize(new Dimension(500, 500));
    makeMap();

}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    for (int x = 25; x <= 500; x += 25) {
        for (int y = 25; y <= 500; y += 25) {
            g.drawRect(0, 0, x, y);
        }
    }
    for (int i = 2; i <= 399; i++) {
        int rand = (int) ((Math.random() * (7)) + 1);
        if (rand == 1) {
            space = i;
            // System.out.println(space);
            int x = 0;
            int y = 0;
            space -= 1;
            if ((space / 20.0) >= 1.0) {
                x = space % 20;
                y = space / 20;
                x *= 25;
                y *= 25;
                g.setColor(Color.BLACK);
                g.fillRect(x, y, 25, 25);
            } else {
                y = space;
                y *= 25;
                g.setColor(Color.BLACK);
                g.fillRect(y, 0, 25, 25);
            }
            mapInfo.put(i, 1);
        }
        if ((rand == 2) || (rand == 3)) {
            mapInfo.put(i, 2);
        } else if (rand == 4) {
            mapInfo.put(i, 3);
        } else {
            mapInfo.put(i, 0);
        }
    }
    mapInfo.put(1, 1234);
    mapInfo.put(400, 1234);
}

public void makeMap() {
    frame = new JFrame();
    panel = new JPanel();
    frame.getContentPane().add(panel);
    frame.pack();
    frame.setVisible(true);
    frame.setTitle("MAP");
    frame.setBounds(600, 0, 516, 538);
    frame.setResizable(false);
    panel.setLayout(new BorderLayout());
    panel.add(this);
}

public void blockSpace(int space) {

}

public int getEvent(int space) {
    return mapInfo.get(space);
}

public static void setPlayerPos() {
    g.setColor(Color.BLUE);
    g.fillRect(475, 475, 25, 25);
}

}

0 个答案:

没有答案
相关问题